是否可以假设pthread_cond_signal会根据互斥体绑定到条件变量的方式自动唤醒信号线程? [英] Can it be assumed that `pthread_cond_signal` will wake the signaled thread atomically with regards to the mutex bond to the condition variable?

查看:116
本文介绍了是否可以假设pthread_cond_signal会根据互斥体绑定到条件变量的方式自动唤醒信号线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用POSIX :

pthread_cond_broadcast()pthread_cond_signal()函数可由线程调用,无论它当前是否拥有调用pthread_cond_wait()pthread_cond_timedwait()的线程在等待期间与条件变量相关联的互斥锁;但是,如果需要可预测的调度行为,则该互斥锁应由调用pthread_cond_broadcast()pthread_cond_signal()的线程锁定.

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().

如果需要可预测的调度行为".这可能/将暗示在调用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?

推荐答案

不,不能保证发出信号的线程将被唤醒.更糟糕的是,如果在信令线程中有序列:

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);
}

由于调度程序中的逻辑,存在合理的机会控制永远不会传递给等待mutex的其他线程.您可以在此答案中找到一些可以玩的示例.

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.

这篇关于是否可以假设pthread_cond_signal会根据互斥体绑定到条件变量的方式自动唤醒信号线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆