std::recursive_mutex

A recursive mutex increments the integer stored inside the mutex each time the same thread calls the lock() function without causing the lock() function to wait. For example, if the mutex is released (that is, the integer in the mutex is 0), when thread #1 calls the lock() function, the integer in the mutex is set to 1. Normally, if thread #1 calls the lock() function again, the lock() function would see that the integer is 1 and enter a wait state until the integer is set to 0. Instead, a recursive mutex will determine which thread is calling the lock() function, and, if the thread that acquired the mutex is the same thread calling the lock() function, the integer in the mutex is incremented again (now resulting in 2) using an atomic operation. For the mutex to be released, the thread must call unlock(), which decrements the integer using an atomic operation, until the integer in the mutex is 0.

The recursive mutex allows the same thread to call the lock() function as many times as it wants, preventing multiple calls to the lock() function and resulting in deadlock at the expense that the lock() and unlock() functions must include an added function call to get the thread's id() instance, so that the mutex can determine which thread is calling lock() and unlock().

For example, consider the following code snippet:

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

std::recursive_mutex m{};

void foo()
{
m.lock();
m.lock();

std::cout << "The answer is: 42 ";

m.unlock();
m.unlock();
}

int main(void)
{
std::thread t1{foo};
std::thread t2{foo};

t1.join();
t2.join();

return 0;
}

The preceding example results in the following:

In the preceding example, we define a function that calls the lock() function for a recursive mutex twice, outputs to stdout, and then calls the unlock() function twice. We then create two threads that execute this function, resulting in no corruption to stdout and no deadlock.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset