From the course: Complete Guide to Parallel and Concurrent Programming with C++

Unlock this course with a free trial

Join today to access over 24,800 courses taught by industry experts.

Deadlock: C++ demo

Deadlock: C++ demo

- [Instructor] To demonstrate a deadlock, we've created this example program that simulates two dining philosophers thinking and eating sushi. The philosopher function on line nine takes two reference parameters named first_chopstick and second_chopstick, which indicate the order in which the philosopher will lock the two mutexes. The while loop on line 10 will continue to run as long as the sushi_count variable is positive, which represents the amount of sushi left on the shared plate between the philosophers. We initialized the sushi count to 5000 on line seven, so our two philosophers should both end up very well fed. Within the while loop, the philosopher will pick up and acquire a lock on their first_chopstick, followed by their second_chopstick, at which point, they're in the critical section. If there's still sushi left on the plate, they'll take a piece by decrementing the sushi_count variable line 14, then finally unlock both chopsticks to put them down for someone else to…

Contents