question

Namk-6027 avatar image
0 Votes"
Namk-6027 asked IgorTandetnik-1300 answered

unique_lock class "_Validate()" problem in mutex header

 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++
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

IgorTandetnik-1300 avatar image
0 Votes"
IgorTandetnik-1300 answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.