提升::condition_variable并锁定

boost::condition_variable and lock

本文关键字:锁定 variable condition 提升      更新时间:2023-10-16
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_onenotify_all的任何要求;所以当你发出condition_variable信号时不握住锁是可以的。但是,信令线程通常需要保持锁,直到它在唤醒后设置等待线程检查的条件。如果没有,该计划可能包含种族。有关示例,请参阅此 SO 问题:提升同步。

thread2醒来时,它将尝试重新获取锁。如果thread1持有锁,thread2将阻止,直到thread1释放锁。

在此处显示的代码中,这不会显著影响行为。如果要在 cond.notify_one(); 之后在 thread1 中添加任何行为,则保证该行为仅在第二个代码块中thread2继续之前执行。

或者,您可以在进入 for 循环之前构造唯一锁 thread2,而不是在等待条件变量之前。这将确保thread1在尝试构建自己的唯一锁时阻塞,直到thread2等待信号,前提是thread1在初始化自身并进入循环之前thread2没有执行。这将允许您保证thread1不会发送任何thread2未等待的通知。