unique_lock class "_Validate()" problem in mutex header

Namk 21 Reputation points
void lock() { // lock the mutex
        _Owns = true;

void _Validate() const { // check if the mutex can be locked
        if (!_Pmtx) {

        if (_Owns) {

this code is unique_lock member functions in mutex header

checking _Owns cannot block "call _Pmtx->lock() duplicated" perfectly.
checking and setting _Owns must be operated at once.
am I thinking wrong?

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,627 questions
0 comments No comments
{count} votes

Accepted answer
  1. Igor Tandetnik 1,106 Reputation points

    unique_lock itself is not thread-safe, nor is it meant to be. You are not supposed to access the same unique_lock instance from multiple threads. It is of course perfectly reasonable to access the same underlying std::mutex instance from multiple threads, whether directly or via distinct unique_lock instances that each thread owns.

    Therefore, members of unique_lock do not need to be protected against concurrent access. It is not necessary that _Pmtx->lock(); and _Owns = true; be performed atomically.

    If your concern is that the same thread could create two separate unique_lock instances that both lock the same mutex - well, yes it could. Such a program would exhibit undefined behavior. It indeed won't be noticed by either unique_lock instance checking its own _Owns member. So don't do that.

    0 comments No comments

0 additional answers

Sort by: Most helpful