boost :: condition_variable和lock [英] boost::condition_variable and lock

查看:141
本文介绍了boost :: condition_variable和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 ?

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.

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

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