gpt4 book ai didi

c++ - boost 条件变量

转载 作者:行者123 更新时间:2023-11-27 22:57:25 26 4
gpt4 key购买 nike

我想使用 boost 条件变量作为同步机制,但在那种情况下:

boost::condition_variable cond;
boost::mutex mutex;

void worker_func()
{
cond.notify_all();
std::cout << "After notify" << std::endl;
}

void main()
{
boost::mutex::soped_lock lock(mutex);
boost::thread work(worker_func);
boost::this_thread::sleep_for(boost::chrono::milliseonds(500));
cond.wait(lock); // here is deadlock
}

当我们在等待条件之前“触发”条件时,就会出现死锁。如果有一个很好的解决方案来编写提供 bool 原子的包装器,它“记住”以前触发过的条件,或者有其他更好的方法来做到这一点?

包装示例:

class Cond_wrap
{
private:
boost::condition_variable cond;
boost::mutex mutex;
bool work_to_do;
public:
Cond_wrap()
{
boost::mutex::scoped_lock(mutex);
work_to_do = false;
}
void notify_all()
{
boost::mutex::scoped_lock(mutex);
work_to_do = true;
cond.notify_all();
}
void wait()
{
boost::mutex::scoped_lock lock(mutex);
if(!work_to_do)
{
cond.wait(lock);
work_to_do = true;
}
else
{
return;
}
}
bool timed_wait(unsigned int timeout)
{
boost::mutex::scoped_lock lock(mutex);
if(!work_to_do)
{
if(cond.timed_wait(lock, boost::chrono::milliseonds(timeout)))
{
work_to_do = true;
return true;
}
else
{
return false;
}
}
else
{
return false;
}
};

Cond_wrap condition_wrap;

void worker_func()
{
{
condition_wrap.notify_all();
}
std::cout << "After notify" << std::endl;
}

int main()
{
boost::thread work(worker_func);
work.detach();

{
boost::this_thread::sleep_for(boost::chrono::milliseonds(500));
condition_wrap.wait();
//there is work to do
}
return 0;
}

最佳答案

这不是条件变量的工作方式。条件变量应具有关联的条件。该条件是在持有互斥量的情况下进行评估的,因此不可能发生竞争,因此您不需要等待。

请注意,虚假唤醒的可能性也需要此条件。

条件变量也应该从持有锁的线程中得到通知。在持有锁的情况下生成新线程可能不是一个好主意。我喜欢添加大括号来清楚地说明锁定代码的范围。

boost::condition_variable cond;
boost::mutex mutex;
bool work_to_do = false;

void worker_func()
{
{
boost::mutex::scoped_lock lock(mutex);
work_to_do = true,
cond.notify_all();
}
std::cout << "After notify" << std::endl;
}

int main()
{
boost::thread work(worker_func);

{
boost::mutex::scoped_lock lock(mutex);
boost::this_thread::sleep_for(boost::chrono::milliseonds(500));
while (!work_to_do)
cond.wait(lock); // no deadlock
//there is work to do
work_to_do = false;
}
}

请注意,在我的代码中,work_to_do 变量如何始终与持有的锁一起使用,对 notify_all() 的调用也是如此。另请注意,cond.wait() 是在循环中调用的,因此虚假唤醒不会破坏乐趣。

附言。只是对 void main() 说不。

关于c++ - boost 条件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31409065/

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