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();
}
}
Run Code Online (Sandbox Code Playgroud)
我怀疑是关于互斥锁,我只需要互斥对象?
编辑:
cb是循环缓冲区.我想实现一种生产者 - 消费者模式
我是否必须使用相同的互斥锁进行wait和notify_one?
假设你使用的是最新版本的boost,那就和我boost::condition一样boost::condition_variable_any,我相信它是一样的std::condition_variable_any.
如果所有这些都是真的,或者至少大约是真的,那么你的代码应该编译,但如果cond.wait(mutex)用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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的实现支持它,替代std了boost.这个:
cb.condition_variable而不是更昂贵(更灵活)condition_variable_any.在你的例子中,我没有看到后者的需要.| 归档时间: |
|
| 查看次数: |
7151 次 |
| 最近记录: |