提高:: condition_variable和锁定 [英] boost::condition_variable and lock

查看:157
本文介绍了提高:: condition_variable和锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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前省略了锁()?

Is there an impact if I omit the lock before calling cond.notify_one() ?

推荐答案

在C ++ 11标准没有规定任何要求 notify_one notify_all ;所以当你一个信号是condition_variable罚款不持有锁。然而,它往往是必要的信令线程持有锁,直到它设置它唤醒后等待的线程检查的条件。如果不是这样,该程序可以包含比赛。有关示例,请参阅本SO问题:升压同步

The C++11 standard does not state any requirement for notify_one and notify_all; so not holding the lock when you signal a condition_variable is fine. However, it's often necessary for the signaling thread to hold the lock until it sets the condition checked by the waiting thread after it's woken up. If it does not, the program may contain races. For an example, see this SO question: Boost synchronization.

这篇关于提高:: condition_variable和锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆