Deadlock Bugs

This lesson introduces deadlocks with examples and then presents conditions for a deadlock to occur.

We'll cover the following...

Beyond the concurrency bugs mentioned in the previous lesson, a classic problem that arises in many concurrent systems with complex locking protocols is known as deadlock. Deadlock occurs, for example, when a thread (say Thread 1) is holding a lock (L1) and waiting for another one (L2); unfortunately, the thread (Thread 2) that holds lock L2 is waiting for L1 to be released. Here is a code snippet that demonstrates such a potential deadlock:

Press + to interact
Thread 1: Thread 2:
pthread_mutex_lock(L1); pthread_mutex_lock(L2);
pthread_mutex_lock(L2); pthread_mutex_lock(L1);

Note that if this code runs, deadlock does not necessarily occur; rather, it may occur if, for example, Thread 1 grabs lock L1 and then a context switch occurs to Thread 2. At that point, Thread 2 grabs L2, and tries to acquire L1. Thus we have a deadlock, as each thread is waiting for the other and neither can run. See the figure below for a graphical depiction; the presence of a cycle in the graph is indicative of ...

Access this course and 1400+ top-rated courses and projects.