Can it be assumed that `pthread_cond_signal` will wake the signaled thread atomically with regards to the mutex bond to the condition variable?

主宰稳场 提交于 2019-12-01 14:43:07

We will se if any PThreads guru has a more comprehensive answer, but as far as I can see, at least in the Linux manpage, you do not get fully predictable behavior. What you do get is a guarantee that if two threads wait on the same condition variable, the higher-prio thread gets to go first (at least, that should be true on Linux if one thread is SCHED_OTHER and the other is real-time SCHED_FIFO). That holds if you lock mutex before signalling (with reservation for errors after a quick read of the manpage).

See https://linux.die.net/man/3/pthread_cond_signal

No, there is no guarantee the signalled thread will be waken up. Worse, if in the signalling thread you have sequence:

while(run_again) {
    pthread_mutex_lock(&mutex);
    /* prepare data */
    pthread_mutex_unlock(&mutex);
    pthread_cond_broadcast(&cond);
}

there is reasonable chance control would never be passed to other threads waiting on mutex because of logic in the scheduler. Some examples to play with you can find in this answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!