#include #include #include #include std::mutex cout_mutex; class Philosopher { public: Philosopher(unsigned int id_, std::mutex& left_fork_, std::mutex& right_fork_) : id(id_), left_fork(left_fork_), right_fork(right_fork_) { } void operator()() { for (int i = 0; i < 5; ++i) { print_status("sits down at the table"); { std::unique_lock lock1(left_fork, std::defer_lock); std::unique_lock lock2(right_fork, std::defer_lock); std::lock(lock1, lock2); print_status("picks up both forks and is dining"); } print_status("returns his forks and leaves the table"); } } private: void print_status(const std::string& msg) const { std::lock_guard lock(cout_mutex); std::cout << "philosopher [" << id << "]: " << msg << std::endl; } unsigned int id; std::mutex& left_fork; std::mutex& right_fork; }; int main() { constexpr unsigned int PHILOSOPHERS = 5; std::thread philosopher[PHILOSOPHERS]; std::mutex fork[PHILOSOPHERS]; for (int i = 0; i < PHILOSOPHERS; ++i) { philosopher[i] = std::thread(Philosopher(i+1, fork[i], fork[(i + PHILOSOPHERS - 1) % PHILOSOPHERS])); } for (int i = 0; i < PHILOSOPHERS; ++i) { philosopher[i].join(); } }