Sobes.tech
Middle+

What is a recursive mutex?

sobes.tech AI

Answer from AI

A recursive (or reentrant) mutex is a type of synchronization primitive that allows a thread that already owns the mutex to lock it again without causing a deadlock.

Main features:

  • Multiple locking: The same thread can call lock() (or an equivalent function) on a recursive mutex multiple times.
  • Ownership counter: The mutex maintains a counter that increases with each re-lock by the owning thread.
  • Unlocking: The mutex becomes fully free only after the owner thread calls unlock() (or an equivalent function) the same number of times as it was locked.
  • Non-blocking threads: Other threads attempting to acquire the recursive mutex while it is busy will be blocked until the owning thread releases it completely.

Usage:

  • Useful in recursive functions or when calling methods of one object from another, where both methods require locking the same mutex.
  • Allows avoiding deadlocks in scenarios where a thread already holds a lock and tries to acquire it again.

Example in C++11 with std::recursive_mutex:

#include <mutex>
#include <thread>
#include <iostream>

std::recursive_mutex recursiveMutex;

void recursiveFunction(int depth) {
    recursiveMutex.lock(); // Reentrant lock
    if (depth > 0) {
        std::cout << "Thread ID: " << std::this_thread::get_id() << ", Depth: " << depth << std::endl;
        recursiveFunction(depth - 1); // Recursive call
    }
    recursiveMutex.unlock(); // Unlock
}

int main() {
    std::thread t(recursiveFunction, 3);
    t.join();
    return 0;
}