快速连续 notify_all()s 不会解锁 condition_variable?

Quick consecutive notify_all()s won't unlock condition_variable?

我有如下一段代码:

#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

简而言之,这两个通知发生在任何线程唤醒之前。

一旦条件变量被通知,所有线程都被唤醒(或者至少条件变量不再考虑它们'waiting')。在他们下次调用 wait() 之前发生的后续通知将什么都不做。

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

通知不排队。只有当前正在等待的东西才能得到它们,等待的东西可以在等待时虚假地醒来。

条件变量不是信号量:除非对并发性做更多的推理而不是健康的,它们应该总是等待测试,在互斥体中修改和读取测试值,并在完成锁的情况下修改测试值在通知之前,通知应该只是为了检查受保护的值(提取所有信息)。

您违反了这些规则,您的代码没有按照您的预期运行。对我来说,如果您的代码有效,那将是令人惊讶的。

值、条件变量、互斥量:三部分,一条消息。