unique_lock class "_Validate()" problem in mutex header

Namk 21 Reputation points
2021-10-07T08:27:07.407+00:00
void lock() { // lock the mutex
        _Validate();
        _Pmtx->lock();
        _Owns = true;
}

void _Validate() const { // check if the mutex can be locked
        if (!_Pmtx) {
            _Throw_system_error(errc::operation_not_permitted);
        }

        if (_Owns) {
            _Throw_system_error(errc::resource_deadlock_would_occur);
        }
}

↑↑↑↑
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?

C++
C++
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,541 questions
0 comments No comments
{count} votes

Accepted answer
  1. Igor Tandetnik 1,106 Reputation points
    2021-10-07T13:55:20.35+00:00

    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