Quantcast
Channel: GCC C++11 Condition Variable Wait Internals - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Casey for GCC C++11 Condition Variable Wait Internals

$
0
0

The function (which I believe to be std::condition_variable_any<_Lock>::wait) is avoiding deadlock by establishing a lock ordering invariant that __lock must be locked before acquiring _M_mutex. While doing so, it must somehow still guarantee that __lock is not held while waiting on the internal condition variable _M_cond. Note that _Unlock<_Lock> is an RAII unlocking object. It performs the opposite function of the usual lock guards by unlocking in its constructor and locking in the destructor. The necessary ordering of events is:

  1. acquire __lock (pre-condition of the wait call)
  2. acquire _M_mutex (in the __my_lock constructor)
  3. release __lock (in the __unlock constructor)
  4. atomically release _M_mutex and wait on _M_cond (happens in _M_cond.wait)
  5. reacquire _M_mutex on wakeup (also in _M_cond.wait)
  6. release _M_mutex (in the __my_lock2 destructor)
  7. reacquire __lock (in the __unlock destructor)

The move from __my_lock to __my_lock2 is necessary so that __my_lock2 will be destroyed before __unlock ensuring that event 6 happens before 7 instead of after.


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>