From the course: Parallel and Concurrent Programming with C++ Part 1

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Livelock: C++ demo

Livelock: C++ demo - C++ Tutorial

From the course: Parallel and Concurrent Programming with C++ Part 1

Start my 1-month free trial

Livelock: C++ demo

- [Instructor] To demonstrate a livelock scenario, we'll modify our original dining philosophers example. It creates two philosopher threads Barron and Olivia, which each grab a different first and second chopstick, and therefore have the potential to end up in a deadlock. So, let's be clever and implement our own deadlock avoidance algorithm. I'll change the lock function on line 12 for the second chopstick from a regular lock to try_lock. And then I'll make that call to try_lock the condition for an if statement. If the second chopstick was already taken by another thread, try_lock will return false. In that case, this philosopher should politely put back their first chopstick by unlocking it, so another philosopher can take it. Otherwise, if the current thread successfully locked both chopsticks, it can continue on as normal, taking a piece of sushi and then unlocking both chopsticks. So, I'll enclose that within an else…

Contents