void* philospher(void* args) { size_t id = *(size_t*)args; size_t first_chopstick = (id == n - 1 ? 0 : id); size_t second_chopstick = (id == n - 1 ? id : id + 1); for (size_t i = 0; i < 3; i++) { chopsticks[first_chopstick].lock(); chopsticks[second_chopstick].lock(); activity_lock.lock(); activities[id] = eating; print_activities(); std::cout << id << " starts eating" << std::endl; activity_lock.unlock(); // eat sleep(2 + (rand() % 3)); chopsticks[second_chopstick].unlock(); chopsticks[first_chopstick].unlock(); activity_lock.lock(); activities[id] = thinking; print_activities(); std::cout << id << " stops eating" << std::endl; activity_lock.unlock(); // think sleep(2 + (rand() % 8)); } return nullptr; }
int main() { int start[] = {1, 3, 1, 5, 8, 6}; int finish[] = {2, 6, 6, 7, 10, 8}; int n = sizeof(start) / sizeof(start[0]); print_activities(start, finish, n); return 0; }