boost :: condition_variable并锁定

时间:2012-02-02 19:39:39

标签: c++ multithreading boost

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()之前省略了锁,是否有影响?

2 个答案:

答案 0 :(得分:3)

C ++ 11标准没有规定对notify_onenotify_all的任何要求;因此,当您发出condition_variable信号时,不要按住锁定。但是,信号线程通常需要保持锁定,直到它在唤醒之后设置由等待线程检查的条件为止。如果没有,该程序可能包含比赛。例如,请参阅此SO问题:Boost synchronization

答案 1 :(得分:2)

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

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

或者,您可以在进入for循环之前在thread2中构造唯一锁,而不是在等待条件变量之前。这将确保thread1thread2等待信号之前尝试构建自己的唯一锁时阻止thread1,前提是thread2thread1初始化之前未执行{进入循环。这样您就可以保证thread2不会发送{{1}}不等待的任何通知。

相关问题