正确使用boost::wait boost::condition

correct use of boost::wait boost::condition

本文关键字:boost condition wait      更新时间:2023-10-16
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::conditionboost::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。:

  1. 不使用递归互斥锁。请确保不要尝试递归地锁定它。
  2. 使用互斥锁保护对容器cb的访问。
  3. 在等待时使用while循环来防止虚假唤醒。
  4. 使用更便宜的condition_variable代替更昂贵(更灵活)的condition_variable_any。在您的示例中,我不认为需要后者。

正确-你需要一个互斥锁;它的目的是确保多个消费者相对于你的一个生产者是同步的。

另见http://www.boost.org/doc/libs/1_41_0/doc/html/thread/synchronization.html