gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:30:34 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com