Can unique_lock be used with a recursive_mutex?
A common mistake is to confuse the mutex
with the lock
. A mutex
is an object that can be shared among threads (otherwise it would be useless). A lock however is not itself a thread-safe object. It should not be shared among threads. It is typically a local object on a stack. For example:
void foo(){ std::unique_lock<std::mutex> lk(mut); // mut comes from some other scope // mut locked here // ...} // mut unlocked here
In the example above, if foo()
is called recursively, you have undefined behavior because you will lock mut
recursively. On each recursion, you get a new unique_lock
though. So the unique_lock
is not aware of the recursion. If you really need to call foo()
recursively, you need to use a recursive mutex, for example:
void foo(){ std::unique_lock<std::recursive_mutex> lk(mut); // mut comes from some other scope // mut locked here // ...} // mut unlocked here
So: Yes, you can use std::unique_lock<std::recursive_mutex>
, and yes, your implementation is correct.