提升::condition_variable并锁定
boost::condition_variable and lock
boost::condition_variable cond;
boost::mutex mut;
//thread1
{
"read_socket()"
cond.notify_one();
}
//thread2
{
for(;;)
{
...
boost::unique_lock<boost::mutex> lock(mut);
cond.wait(lock);
}
}
对
boost::condition_variable cond;
boost::mutex mut;
//thread1
{
"read_socket()"
boost::unique_lock<boost::mutex> lock(mut);
cond.notify_one();
}
//thread2
{
for(;;)
{
...
boost::unique_lock<boost::mutex> lock(mut);
cond.wait(lock);
}
如果在调用 cond.notify_one(( 之前省略锁会有什么影响吗?
C++11 标准没有规定对notify_one
和notify_all
的任何要求;所以当你发出condition_variable信号时不握住锁是可以的。但是,信令线程通常需要保持锁,直到它在唤醒后设置等待线程检查的条件。如果没有,该计划可能包含种族。有关示例,请参阅此 SO 问题:提升同步。
当thread2
醒来时,它将尝试重新获取锁。如果thread1
持有锁,thread2
将阻止,直到thread1
释放锁。
在此处显示的代码中,这不会显著影响行为。如果要在 cond.notify_one();
之后在 thread1
中添加任何行为,则保证该行为仅在第二个代码块中thread2
继续之前执行。
或者,您可以在进入 for 循环之前构造唯一锁 thread2
,而不是在等待条件变量之前。这将确保thread1
在尝试构建自己的唯一锁时阻塞,直到thread2
等待信号,前提是thread1
在初始化自身并进入循环之前thread2
没有执行。这将允许您保证thread1
不会发送任何thread2
未等待的通知。
相关文章:
- C++ Singleton - Prevent ::instance() to variable
- 如何找到锁定Linux futex的C++行
- G锁定铸造到基础上会释放模拟行为
- 如何检查线程是否锁定
- 如何在C++中找到active directory中禁用和锁定的窗口帐户
- 我应该在锁定TBitmap画布后解锁它吗
- 如何通过多类"Union variable" (sfml) 使用轮询事件
- C++ 11 中的锁定是否保证访问数据的新鲜度?
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 为什么我会收到"Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted"错误?
- 如何在实时应用程序中锁定线程
- 在 lambda 中锁定 std::shared_ptr 的复制操作
- C++:寻找"returning address of local variable..."的更正
- 使用简单两相锁定的并发程序
- 锁定来自其他线程的类成员
- 他们如何将红外锁定像素转换为镜头前方 1m 的正常平面上的位置
- 同一互斥锁顺序上的锁定和解锁是否一致?
- 共享内存的升压容器是否实现锁定?
- C++ - 在我尝试制作一个简单的计算器时有一个"uninitialized local variable y used"警告