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

Recursive mutexes

Recursive mutexes

What you'll learn: How to allow a single thread to lock the same mutex multiple times without causing a deadlock.

The problem with standard locks

Imagine a bathroom door with a standard bolt. If you enter and lock it, you are safe. But if you somehow forgot you were already inside and tried to lock the door again from the inside, a standard mutex would "freeze." It sees a lock request on an already-locked door and makes you wait forever for the lock to be released. Since you are the one holding the lock, you’re stuck in a permanent stalemate called a deadlock.

In programming, this often happens during recursion. If Function A locks a mutex and then calls itself, the second instance of Function A will hang indefinitely waiting for the first instance to let go.

The recursive solution

A recursive mutex solves this by keeping track of two things:

  1. Which thread currently holds the lock.
  2. A "lock count" (how many times that thread has locked it).

If the thread that already owns the mutex asks to lock it again, the system simply increments the counter and lets the thread proceed. To fully unlock the mutex, the thread must call unlock the exact same number of times it called lock.

Implementation in C

To use this, you must initialize the mutex with a specific attribute. Here is how you set it up using the pthread library:

#include <pthread.h>
#include <stdio.h>

pthread_mutex_t rec_mutex;

void count_down(int n) {
    pthread_mutex_lock(&rec_mutex);
    printf("Level %d: Lock acquired\n", n);

    if (n > 0) {
        count_down(n - 1); // Recursive call: locks again!
    }

    printf("Level %d: Releasing lock\n", n);
    pthread_mutex_unlock(&rec_mutex);
}

int main() {
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    // Set the mutex type to RECURSIVE
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
    
    pthread_mutex_init(&rec_mutex, &attr);

    count_down(2);

    pthread_mutex_destroy(&rec_mutex);
    pthread_mutexattr_destroy(&attr);
    return 0;
}

When to use them

Recursive mutexes are handy when building complex APIs where multiple functions might call each other, and each needs to ensure thread safety independently. However, use them sparingly. If you find yourself needing recursive locks often, it might be a sign that your function logic is becoming too tangled.

Key takeaway

Recursive mutexes prevent deadlocks by allowing the owning thread to re-acquire the same lock multiple times, provided it unlocks it just as many times.