正确使用 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::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();
}
}
My doubt is about the mutex, I only need on mutex object ?
EDIT:
cb is a circular buffer.
I want to implement a sort of producer-consumer pattern
do I have to use the same mutex for wait and notify_one ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您使用的是最新版本的 boost,
boost::condition
与boost::condition_variable_any
相同,我相信它与std 相同::condition_variable_any
。如果所有这些都是正确的,或者至少近似正确,您的代码应该可以编译,但如果您调用
cond.wait(mutex)
并递归锁定mutex
,则可能会死锁。我建议:
如果您的实现支持它,请将
std
替换为boost
。这:cb
的访问。condition_variable
而不是更昂贵(且更灵活)的condition_variable_any
。在你的例子中我没有看到后者的必要性。Assuming you are using a recent version of boost,
boost::condition
is the same thing asboost::condition_variable_any
, which I believe is the same thing asstd::condition_variable_any
.If all that is true, or at least approximately true, your code should compile, but will probably deadlock if you call
cond.wait(mutex)
withmutex
recursively locked.I recommend instead:
And if your implementation supports it, substitute
std
forboost
. This:cb
.condition_variable
instead of the more expensive (and more flexible)condition_variable_any
. I'm not seeing the need for the latter in your example.正确 - 你需要一个互斥锁;其目的是确保多个消费者与一个生产者同步。
另请参阅 http://www.boost.org/ doc/libs/1_41_0/doc/html/thread/synchronization.html
Correct - you need one mutex; it's purpose will be to make sure that multiple consumers are synchronized with the respect to your one producer.
Also, see http://www.boost.org/doc/libs/1_41_0/doc/html/thread/synchronization.html