By try_lock*
, I take to mean try_lock()
, try_lock_for()
, and try_lock_until()
. According to cppreference, all three methods may just fail spuriously. Following is quoted from the description for try_lock_for()
As with
try_lock()
, this function is allowed to fail spuriously and returnfalse
even if the mutex was not locked by any other thread at some point duringtimeout_duration
.
I know that spurious wakeup may happen with std::condition_variable
and the rationale behind it. But, what is the case with a mutex?
According to: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3209.htm
On the other hand, there are strong reasons to require that programs be written to tolerate spurious try_lock() failures:
- As pointed out in Boehm, Adve, "Foundations of the C++ Concurrency Memory Model", PLDI 08, enforcing sequential consistency for data-race-free programs without spurious try_lock() failures requires significantly stronger memory ordering for lock() operations on try_lock()-compatible mutex types. On some architectures that significantly increases the cost of uncontended mutex acquisitions. This cost appears to greatly outweigh any benefit from prohibiting spurious try_lock() failures.
- It allows a user-written try_lock() to fail if, for example, the implementation fails to acquire a low-level lock used to protect the mutex data structure. Or it allows such an operation to be written directly in terms of compare_exchange_weak.
- It ensures that client code remains correct when, for example, a debugging thread is introduced that occasionally acquires locks in order to be able to read consistent values from a data structure being checked or examined. Any code that obtains information from try_lock() failure would break with the introduction of another thread that purely locks and reads the data structure.