条件变量和消除误解

标签 c multithreading

我注意到在大多数条件变量的示例中,我看到类似的内容:

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/

相关文章:

c - 使用 write() 写入文件时文件被覆盖

c - 无法在 C 函数中将常量字符串作为参数传递

不能在 PIC 12F675 中进行模拟读取

c - 维基百科的读写锁实现是否正确?

java - 尝试在可运行对象中同步方法

c - AVL 树插入(在 C 中)失败

c++ - 使用 clang llvm 检查变量是否在任意源位置具有范围

Python 高性能计算

c - 多个线程如何拥有相同的线程ID?

Python 多线程(while 和 apscheduler)