I have seen some people hate on recursive_mutex
:
http://www.zaval.org/resources/library/butenhof1.html
But when thinking about how to implement a class that is thread safe (mutex protected), it seems to me excruciatingly hard to prove that every method that should be mutex protected is mutex protected and that mutex is locked at most once.
So for object oriented design, should std::recursive_mutex
be default and std::mutex
considered as an performance optimization in general case unless it is used only in one place (to protect only one resource)?
To make things clear, I'm talking about one private nonstatic mutex. So each class instance has only one mutex.
At the beginning of each public method:
{
std::scoped_lock<std::recursive_mutex> sl;
Most of the time, if you think you need a recursive mutex then your design is wrong, so it definitely should not be the default.
For a class with a single mutex protecting the data members, then the mutex should be locked in all the
public
member functions, and all theprivate
member functions should assume the mutex is already locked.If a
public
member function needs to call anotherpublic
member function, then split the second one in two: aprivate
implementation function that does the work, and apublic
member function that just locks the mutex and calls theprivate
one. The first member function can then also call the implementation function without having to worry about recursive locking.e.g.
This is of course a trivial contrived example, but the
increment_data
function is shared between two public member functions, each of which locks the mutex. In single-threaded code, it could be inlined intoincrease_count
, andincrease_count_and_return
could call that, but we can't do that in multithreaded code.This is just an application of good design principles: the public member functions take responsibility for locking the mutex, and delegate the responsibility for doing the work to the private member function.
This has the benefit that the
public
member functions only have to deal with being called when the class is in a consistent state: the mutex is unlocked, and once it is locked then all invariants hold. If you callpublic
member functions from each other then they have to handle the case that the mutex is already locked, and that the invariants don't necessarily hold.It also means that things like condition variable waits will work: if you pass a lock on a recursive mutex to a condition variable then (a) you need to use
std::condition_variable_any
becausestd::condition_variable
won't work, and (b) only one level of lock is released, so you may still hold the lock, and thus deadlock because the thread that would trigger the predicate and do the notify cannot acquire the lock.I struggle to think of a scenario where a recursive mutex is required.