Course contentsShow
← C
Lesson 1128 of 1,21915. Systems ProgrammingFree lesson

Avoiding deadlocks

Avoiding deadlocks

What you'll learn: How to prevent your program from freezing forever by following a consistent locking order when using multiple mutexes.

The "Traffic Jam" of Threads

A deadlock is a situation where two or more threads are stuck waiting for each other, and nobody can move forward.

Imagine two people, Alice and Bob, trying to write a letter. To do this, they need two things: a Pen and Paper.

  1. Alice grabs the Pen.
  2. Bob grabs the Paper.
  3. Alice waits for Bob to finish with the Paper.
  4. Bob waits for Alice to finish with the Pen.

They will sit there forever. Neither can proceed because they are both holding a resource the other person needs. In C, this happens when Thread A locks Mutex 1 and wants Mutex 2, while Thread B has locked Mutex 2 and wants Mutex 1.

The Golden Rule: Hierarchical Locking

The simplest way to avoid this "deadly embrace" is to always acquire locks in the same order.

If every thread agrees that they must pick up the Pen before the Paper, the deadlock vanishes. If Alice grabs the Pen, Bob cannot grab the Paper because he is still waiting for the Pen to become available. He never gets the chance to "block" the Paper from Alice.

Code Example: Order Matters

Here is how we enforce a strict order to keep our program running smoothly.

#include <pthread.h>

pthread_mutex_t mutex_pen = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_paper = PTHREAD_MUTEX_INITIALIZER;

void* write_letter(void* arg) {
    // ALWAYS lock in this specific order: Pen then Paper
    pthread_mutex_lock(&mutex_pen);
    pthread_mutex_lock(&mutex_paper);

    // ... Critical section: Writing the letter ...

    pthread_mutex_unlock(&mutex_paper);
    pthread_mutex_unlock(&mutex_pen);
    
    return NULL;
}

By ensuring every function in your program follows this sequence (Pen → Paper), you guarantee that threads will queue up in a line rather than snatching resources out from under each other. If you have ten mutexes, number them 1 through 10 and ensure your threads always acquire them in increasing numerical order.

Key takeaway

To prevent deadlocks, establish a strict hierarchy for your mutexes and ensure every thread acquires them in the exact same order.