我注意到在大多数条件变量的示例中,我看到类似的内容:
pthread_cond_signal(&cond, &lock);
pthread_mutex_unlock(&lock);
我的问题是为什么要按这个顺序完成。为什么在释放锁之前先广播信号?如果在信号广播和解锁之间发生上下文切换,其他线程将从 sleep 中唤醒,并尝试访问有问题的锁,看到它仍然处于锁定状态,然后返回待机状态,因此信号不会浪费了?
为什么这不是更好的解决方案:
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond, &lock);
在这种情况下,锁会在休眠的线程被唤醒之前释放,因此它们实际上能够访问之前锁定的数据。
有人可以帮我解决这个问题吗?
最佳答案
手册页有答案(强调我的):
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().
关于条件变量和消除误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36000403/