我有以下代码:

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>

std::condition_variable cv;
std::mutex cv_m;  // This mutex is used for three purposes:
                  // 1) to synchronize accesses to i
                  // 2) to synchronize accesses to std::cout
                  // 3) for the condition variable cv
int i = 0;

void waits()
{
  std::unique_lock<std::mutex> lk(cv_m);
  std::cout << "Waiting... \n";
  cv.wait(lk, [] { return i == 1; });
  std::cout << "..waiting... \n";
  cv.wait(lk);
  std::cout << "...finished waiting. i == 1\n";
}

void signals()
{
  for (int j = 0; j < 3; ++j) {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    {
      std::unique_lock<std::mutex> lk(cv_m);
      std::cout << "Notifying...\n";
    }
  }
  i = 1;

  std::this_thread::sleep_for(std::chrono::seconds(1));
  std::cout << "Notifying again...\n";
  cv.notify_all();
  std::cout << "Notifying again2...\n";
  // HERE!
  //std::this_thread::sleep_for(std::chrono::seconds(1));
  cv.notify_all();
}

int main()
{
  std::thread t1(waits), t2(waits), t3(waits), t4(signals);
  t1.join();
  t2.join();
  t3.join();
  t4.join();
}

当我取消注释sleep_for()行时,condition_variable将收到通知,程序将取消阻止并退出。

对此进行评论时,它被阻止了。

为什么会这样呢?

未注释版本的输出:
Waiting...
Waiting...
Waiting...
Notifying...
Notifying...
Notifying...
Notifying again...
Notifying again2...
..waiting...
..waiting...
..waiting...
...finished waiting. i == 1
...finished waiting. i == 1
...finished waiting. i == 1

最佳答案

简短的形式是这两个通知在任何线程唤醒之前发生。

一旦通知了条件变量,所有线程都将唤醒(或者至少条件变量不再将其视为“正在等待”)。在下一次调用wait()之前发生的后续通知将完全不执行任何操作。

通过引入睡眠,您可以给线程足够的时间再次执行wait(),然后再次通知它们,从而产生您所看到的行为。

关于c++ - 快速连续的notify_all()不会解锁condition_variable吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34687713/

10-11 00:20