正确使用boost::wait boost::condition
correct use of boost::wait boost::condition
boost::condition cond;
boost::recursive_mutex mutex;
for(;;)
{
D * d = nullptr;
while( cb.pop(d) )
{
}
boost::lock_guard<boost::recursive_mutex> lock( **mutex** );
cond.wait( **mutex** );
}
while(1)
{
getchar();
for( int i = 0 ; i < 1000 ; ++i )
{
cb.push(new D(i));
boost::lock_guard<boost::recursive_mutex> lock( **mutex** );
cond.notify_one();
}
}
我的疑问是关于互斥锁,我只需要一个互斥锁对象?
编辑:cb是一个循环缓冲区。我想实现一种生产者-消费者模式
我必须为wait和notify_one使用相同的互斥锁吗?
假设您使用的是最新版本的boost, boost::condition
与boost::condition_variable_any
是一样的,我相信这与std::condition_variable_any
是一样的。
如果所有这些都为真,或者至少近似为真,您的代码应该可以编译,但是如果您在mutex
递归锁定的情况下调用cond.wait(mutex)
,则可能会死锁。
我建议改成:
boost::condition_variable cond;
boost::mutex mutex;
// In one thread
for(;;)
{
D * d = nullptr;
boost::unique_lock<boost::mutex> lock( mutex );
while( cb.pop(d) )
{
}
while (cb.empty())
cond.wait( lock );
}
// In another thread
while(1)
{
getchar();
for( int i = 0 ; i < 1000 ; ++i )
{
boost::lock_guard<boost::mutex> lock( mutex );
cb.push(new D(i));
cond.notify_one();
}
}
如果你的实现支持它,用std
代替boost
。:
- 不使用递归互斥锁。请确保不要尝试递归地锁定它。
- 使用互斥锁保护对容器
cb
的访问。 - 在等待时使用while循环来防止虚假唤醒。
- 使用更便宜的
condition_variable
代替更昂贵(更灵活)的condition_variable_any
。在您的示例中,我不认为需要后者。
正确-你需要一个互斥锁;它的目的是确保多个消费者相对于你的一个生产者是同步的。
另见http://www.boost.org/doc/libs/1_41_0/doc/html/thread/synchronization.html
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- boost::进程间消息队列引发错误
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- cmake如何在fedora工作站中找到boost静态库包
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- Boost Graph Library,修复节点大小
- 什么是"#include <boost/functional/hash.hpp> "?
- 基于boost的程序的静态链接——zlib问题
- C++:如何在CLion IDE中安装Boost
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何在boost beast http请求中设置http头
- Boost Spirit,获取迭代器内部语义动作
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- boost::asio如何生成多个协同程序,然后加入它们
- 当我尝试使用 sstream 和分面将 Boost Time_duration转换为字符串时,我没有得到所需的格式
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- boost::asio async condition
- boost::wait和boost::condition必须共享同一个互斥对象吗?
- 正确使用boost::wait boost::condition