Dav*_*vid 7 c++ multithreading condition-variable c++11
我还没有完全围绕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();
Run Code Online (Sandbox Code Playgroud)
这有效...除非我停在一些断点上并放慢速度.当我这样做,我看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();
Run Code Online (Sandbox Code Playgroud)