From C++14 chapter "30.4.1.2 Mutex types"
paragraph 16:
An implementation may fail to obtain the lock even if it is not held by any other thread. [Note: This spurious failure is normally uncommon, but allows interesting implementations based on a simple compare and exchange (Clause 29). —end note] An implementation should ensure that try_lock()
does not consistently return false
in the absence of contending mutex acquisitions.
and paragraph 19:
little would be known about the state after a failure, even in the absence of spurious failures
And in answer to
I know that spurious wakeup may happen with std::condition_variable
and the rationale behind it. But, what is the case with a mutex?
std::timed_mutex
sometimes is implemented using std::condition_varible
when there is no direct support in the OS. As in GNU libstdc++:
#if _GTHREAD_USE_MUTEX_TIMEDLOCK
...
#else // !_GTHREAD_USE_MUTEX_TIMEDLOCK
class timed_mutex
{
mutex _M_mut;
condition_variable _M_cv;
bool _M_locked = false;
public:
template<typename _Rep, typename _Period>
bool
try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
{
unique_lock<mutex> __lk(_M_mut);
if (!_M_cv.wait_for(__lk, __rtime, [&]{ return !_M_locked; }))
return false;
_M_locked = true;
return true;
}
template<typename _Clock, typename _Duration>
bool
try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
{
unique_lock<mutex> __lk(_M_mut);
if (!_M_cv.wait_until(__lk, __atime, [&]{ return !_M_locked; }))
return false;
_M_locked = true;
return true;
}
};
#endif