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-19 11:53:37

问题


Quoting POSIX:

The pthread_cond_broadcast() or pthread_cond_signal() 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 behavior is required, then that mutex shall be locked by the thread calling pthread_cond_broadcast() or pthread_cond_signal().

"If predictable scheduling behavior is required". This could/would hint that locking the mutex bound to the condition variable right before calling pthread_cond_signal() should guarantee that the signaled thread will be woken up before any other thread manages to lock this mutex. Is this correct?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/44212960/can-it-be-assumed-that-pthread-cond-signal-will-wake-the-signaled-thread-atomi

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