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

Common synchronization pitfalls

Common synchronization pitfalls

What you'll learn: How to recognize and avoid the "deadlock," a logical knot where two or more threads wait forever for each other to blink.

The Restaurant Standoff

Imagine two diners, Alice and Bob. To eat their meal, they each need both a knife and a fork. There is only one of each on the table.

If Alice grabs the knife and Bob grabs the fork at the exact same time, they both get stuck. Alice won't give up her knife until she gets the fork, and Bob won't give up his fork until he gets the knife. They sit staring at each other forever. This is a deadlock.

In systems programming, this happens when Thread A holds Mutex 1 and tries to lock Mutex 2, while Thread B holds Mutex 2 and tries to lock Mutex 1.

Deadlock in Code

In the following example, two threads are trying to transfer money between two accounts. If they run simultaneously, they might lock their "own" account first and then wait indefinitely for the other.

#include <pthread.h>

pthread_mutex_t mutex_a = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_b = PTHREAD_MUTEX_INITIALIZER;

void* thread_one_run(void* arg) {
    pthread_mutex_lock(&mutex_a); // Thread 1 takes A
    // ... tiny delay ...
    pthread_mutex_lock(&mutex_b); // Thread 1 waits for B forever
    
    // Perform work
    
    pthread_mutex_unlock(&mutex_b);
    pthread_mutex_unlock(&mutex_a);
    return NULL;
}

void* thread_two_run(void* arg) {
    pthread_mutex_lock(&mutex_b); // Thread 2 takes B
    // ... tiny delay ...
    pthread_mutex_lock(&mutex_a); // Thread 2 waits for A forever
    
    // Perform work
    
    pthread_mutex_unlock(&mutex_a);
    pthread_mutex_unlock(&mutex_b);
    return NULL;
}

The Golden Rule: Lock Ordering

The simplest way to prevent this architectural disaster is Lock Ordering. You must decide on a hierarchy for your mutexes and stick to it religiously.

If both Thread 1 and Thread 2 are programmed to always lock mutex_a before mutex_b, the deadlock vanishes. If Thread 1 has already grabbed mutex_a, Thread 2 will simply wait at the very first line of its code until Thread 1 is completely finished with both locks. No one gets stuck in the middle.

Key takeaway

Deadlocks occur when threads acquire multiple locks in different orders; always acquire your mutexes in a consistent, predefined sequence to keep your program moving.