#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::lock_guard lock1(left_fork); print_status("picks up the left fork"); { std::lock_guard lock2(right_fork); print_status("picks up the right fork"); { print_status("is dining"); } } print_status("returns the right fork"); } print_status("returns the left fork"); print_status("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(); } }