signal on condition variable without holding lock

前端 未结 2 2047
死守一世寂寞
死守一世寂寞 2021-01-05 04:06

So I just found out that it\'s legal to signal a condition variable if you\'re not holding the lock in c++11. That seems to open the door to some nasty race condition:

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-05 04:46

    It is not guaranteed - if you don't want to miss the signal then you must lock the mutex prior to notifying. Some applications may be agnostic about missing signals.

    From man pthread_signal:

    The pthread_cond_signal() or pthread_cond_broadcast() functions may be called by a thread whether or not it currently owns the mutex that threads calling pthread_cond_wait() or pthread_cond_timedwait() have associated with the condition variable during their waits; however, if predictable scheduling behaviour is required, then that mutex is locked by the thread calling pthread_cond_signal() or pthread_cond_broadcast().

提交回复
热议问题