philosopher::philosopher(int id, vector<mutex*> table, unsigned int max_eat, unsigned int max_think, unsigned int iters) : m_id(id), m_table(table), m_eat_dist(1, max_eat), m_think_dist(1, max_think), m_max_iter(iters) { // assign unique locks to both chopsticks m_left = unique_lock<mutex>(*(m_table[m_id]), defer_lock); m_right = unique_lock<mutex>( *(m_table[(m_id + 1) % m_table.size()]), defer_lock); } void philosopher::get_resources() { lock(m_left, m_right); } void philosopher::release_resources() { m_left.unlock(); m_right.unlock(); } void philosopher::run() { for (m_curr_iter = 0; m_curr_iter < m_max_iter; ++m_curr_iter) { if (stopped()) // respect the stop command break; // decide the amount of time to eat and think // think this_thread::sleep_for(think_time); // grab some chopsticks get_resources(); // eat this_thread::sleep_for(eat_time); // put down chopsticks release_resources(); } }