使用condition_variable控制多线程流
Control multithreaded flow with condition_variable
我还没有开始研究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!
,然后挂起,等待thread2
的cv.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();
相关文章:
- 在C++中使用cURL和多线程
- 多线程双缓冲区
- 为什么我的多线程作业队列崩溃
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 为什么一个向量上的多线程操作很慢
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 全局变量 多读取器 一个写入器多线程安全?
- boost::文件系统::recursive_directory_iterator多线程安全
- 如何阻止TensorFlow的多线程
- 如何在多线程中正确使用unique_ptr进行多态性?
- 并发/多线程:是否可以以这种方式生成相同的输出?
- sigwait() 在多线程程序中不起作用
- 多线程程序中出现意外的内存泄漏
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 控制多线程程序中的输出流
- 控制不同的硬件:多线程或不同的东西
- 使用condition_variable控制多线程流
- 控制对多线程程序中字符串对象的访问的最佳方法
- c++:使用多线程在控制台中移动光标