使用condition_variable控制多线程流

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!,然后挂断,等待thread2cv.wait.怎么了?

也许我不应该使用条件变量......周围没有任何条件wait,也没有需要使用互斥锁保护的数据.我该怎么做呢?

Nem*_*emo 5

你走在正确的轨道上......

只需添加一个布尔值(由互斥锁保护,由条件变量指示),表示"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)

  • 不正确......许多线程当然可以在相同的条件变量上等待.您所看到的是一个关于系统如何决定调度线程的工件(以及当多个线程在等待它时如何移交互斥锁).[wait`的语义](http://en.cppreference.com/w/cpp/thread/condition_variable/wait)将释放互斥锁,然后在发出条件信号时再次获取互斥锁. (3认同)
  • 至于解释原始结果,"notify"仅通知已经在条件变量上等待的线程.如果你在没有人等待的时候调用notify,那么当另一个线程试图等待时它会阻塞. (2认同)