Sometimes a function is written that requires one or more mutexes to be locked before entering that function. If this requirement is not specified, the function can be called without taking the relevant locks before entering, which could have catastrophic consequences.
Now, it is possible to specify something like this in the documentation of a function, but I really don’t like that.
I was thinking to specify it in the preconditions for a function (assert’s when entering the function), but what should the condition be?
Even if the std::mutex in C++11 did have a has_lock() function, there still would not be any guarantees that I‘m the one who has the lock.
If you really don’t want to use recursive mutexes and your goal is to figure out whether the current thread is holding a mutex without trying to acquire it, defining a mutex wrapper is probably the simples solution. Here is a wild shot:
And here is a simple example of how to use it: