c++ - 正确使用 boost::wait boost::condition

标签 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();
    }
}

我的疑问是关于互斥量,我只需要互斥量对象?

编辑:

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。在您的示例中,我没有看到对后者的需求。

关于c++ - 正确使用 boost::wait boost::condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6724280/

相关文章:

c++ - 将 const unsigned long 流式传输到 fstream

c++ - 如何从 boost::thread 中检索线程 ID?

c++ - 使用 boost::bind 在 std::map 中调用仿函数

c++ - 从信号处理程序打印堆栈跟踪

c++ - 按值或按引用传递 C++ 字符串

c++ - C++ 中的 constexpr 是什么?

c++ - 范围互斥锁的自定义 RAII C++ 实现

c++ - Boost:在单独的加载/保存函数中非侵入式地序列化一个类

go - 在 golang 中使用互斥量管理 slice 以提高性能

c - 如何使队列线程安全