std::recursive_mutex won't deadlock when the same thread locks it multiple times.
Will it deadlock when multiple threads lock it multiple times?
Will it deadlock when multiple threads lock it multiple times?
That cannot happen.
By definition a mutex is locked by at most one thread. And a std::recursive_mutex is some kind of mutex. Otherwise it does not comply to its goal of mutual exclusion, since it should be some kind of Mutex concept.
So another thread is not even allowed to lock it a single time. When it does, that other thread stays blocked (till the lock is released - as many times as it was recursively locked).
FYI, here is a simplistic implementation of a recursive mutex:
static const std::thread_id NO_THREAD;
class recursive_mutex {
public:
void lock() {
auto me = std::this_thread::get_id();
if (owner != me) {
mtx.lock();
owner = me;
assert(count == 0);
}
count++;
}
void unlock() {
auto me = std::this_thread::get_id();
assert(owner == me);
assert(count > 0);
count--;
if (count == 0) {
owner = NO_THREAD;
mtx.unlock();
}
}
private:
std::mutex mtx;
std::thread::id owner;
unsigned count{0};
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With