About pthread_cond_signal and pthread_cond_wait

前端 未结 2 1746
一向
一向 2021-01-03 16:37

I have questions about pthread_cond_signal and pthread_cond_wait. For example, in the code below, According to my understanding, when

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 16:45

    pthread_cond_wait() unlocks the mutex on entry and locks it again on exit. If another thread acquires the lock during that time, pthread_cond_wait() cannot return until that other thread has released the lock.

    So, if watch_count() is blocked in pthread_cond_wait(), and inc_count() runs and calls pthread_cond_signal(), then watch_count() will not return from pthread_cond_wait() until inc_count() has called pthread_mutex_unlock().

    However, pthread_cond_wait() can wake even if not signalled. This is called a spurious wake-up. watch_count() can therefore execute count+=125 many times, even if inc_count() never runs, or never calls pthread_cond_signal().

提交回复
热议问题