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

Gui*_*e07 3 c++ boost mutex

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?

How*_*ant 6

假设你使用的是最新版本的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)

如果您的实现支持它,替代stdboost.这个:

  1. 不使用递归互斥锁.请确保您不要尝试递归锁定它.
  2. 使用互斥锁来保护对容器的访问cb.
  3. 在等待期间使用while循环来防止虚假唤醒.
  4. 使用便宜得多condition_variable而不是更昂贵(更灵活)condition_variable_any.在你的例子中,我没有看到后者的需要.