C++14 seems to have omitted a mechanism for checking whether an std::mutex
is locked or not. See this SO question:
https://stackoverflow.com/questions/21892934/how-to-assert-if-a-stdmutex-is-locked
There are several ways around this, e.g. by using;
std::mutex::try_lock()
std::unique_lock::owns_lock()
But neither of these are particularly satisfying solutions.
try_lock()
is permitted to return a false negative and has undefined behaviour if the current thread has locked the mutex. It also has side-effects. owns_lock()
requires the construction of a unique_lock
on top of the original std::mutex
.
Obviously I could roll my own, but I'd rather understand the motivations for the current interface.
The ability to check the status of a mutex (e.g. std::mutex::is_locked()
) does not seem like an esoteric request to me, so I suspect the Standard Committee deliberately omitted this feature rather than it being an oversight.
Why?
Edit: Ok so maybe this use case isn't as common as I had expected, so I'll illustrate my particular scenario. I have a machine learning algorithm which is distributed on multiple threads. Each thread operates asynchronously, and returns to a master pool once it has completed an optimisation problem.
It then locks a master mutex. The thread must then pick a new parent from which to mutate an offspring, but may only pick from parents which do not currently have offspring that are being optimised by other threads. I therefore need to perform a search to find parents that are not currently locked by another thread. There is no risk of the status of the mutex changing during the search, as the master thread mutex is locked. Obviously there's other solutions (I'm currently using a boolean flag) but I thought the mutex offers a logical solution to this problem, as it exists for the purpose of inter-thread synchronization.
is_locked
?