使用condition_variable控制多线程流

Control multithreaded flow with condition_variable

本文关键字:多线程 控制 variable condition 使用      更新时间:2023-10-16

我还没有开始研究C++11多线程的东西,但我正在尝试让多个线程等待主线程上的某个事件,然后所有线程同时继续(处理发生的事情),并在处理完后再次wait。。。循环直到它们关闭。下面并不完全是这样——这是我的问题的一个更简单的再现:

std::mutex mutex;
std::condition_variable cv;
std::thread thread1([&](){ std::unique_lock<std::mutex> lock(mutex); cv.wait(lock);  std::cout << "GO1!n"; });
std::thread thread2([&](){ std::unique_lock<std::mutex> lock(mutex); cv.wait(lock);  std::cout << "GO2!n"; });
cv.notify_all(); // Something happened - the threads can now process it
thread1.join();
thread2.join();

这很有效。。。除非我在一些断点上停下来,放慢速度。当我这样做时,我看到Go1!,然后挂起,等待thread2cv.wait。怎么了?

也许我无论如何都不应该使用条件变量。。。wait周围没有任何条件,也没有需要使用互斥对象保护的数据。我该怎么办?

你走在了正确的轨道上。。。

只需添加一个布尔值(受互斥对象保护,由条件变量表示),表示"go":

std::mutex mutex;
std::condition_variable cv;
bool go = false;
std::thread thread1([&](){ std::unique_lock<std::mutex> lock(mutex); while (!go) cv.wait(lock);  std::cout << "GO1!n"; });
std::thread thread2([&](){ std::unique_lock<std::mutex> lock(mutex); while (!go) cv.wait(lock);  std::cout << "GO2!n"; });
{
    std::unique_lock<std::mutex> lock(mutex);
    go = true;
    cv.notify_all(); // Something happened - the threads can now process it
}
thread1.join();
thread2.join();