在等待之前必须检查 std::condition_variable 谓词吗?

bre*_*att 2 c++ multithreading mutex c++11 c++14

从文档语言中我不清楚是否必须在等待之前检查 std::condition_variable 的谓词。

cppreference上,有这样的语句:

Any thread that intends to wait on std::condition_variable has to
    1. ...
    2. check the condition, in case it was already updated and notified 
Run Code Online (Sandbox Code Playgroud)

实际上,似乎不需要检查。我只是担心如果不这样做的话会出现未定义的行为。

我关心的情况是消费者在生产者之后上线(即条件变量在另一个线程开始等待之前已被一个线程通知):

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

int main() {
  std::condition_variable condition_var;
  std::mutex mutex;
  std::vector<std::thread> threads;
  bool flag = false;

  // Producer
  threads.emplace_back([&]() {
    {
      std::lock_guard<std::mutex> lock(mutex);
      flag = true;
      printf("%s\n", "flag = true");
    }
    condition_var.notify_all();
  });

  // Consumer
  threads.emplace_back([&]() {
    std::this_thread::sleep_for(std::chrono::seconds(3));
    {
      std::unique_lock<std::mutex> lock(mutex);
      condition_var.wait(lock, [&]() { return flag; });
      printf("%s\n", "Consumer finished");
    }
  });

  for (auto& thread : threads) {
    if (thread.joinable()) {
      thread.join();
    }
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,生产者启动并通知条件变量。之后消费者启动,并在检查条件变量之前休眠几秒钟。这实际上确保了消费者在生产者通知条件变量之后开始等待。

尽管如此,代码在我的计算机上完成并且不会无限期地挂起。事实上,由于它完成的速度很快,我认为这不是由于虚假唤醒造成的,但我不确定如何检查。

Ast*_*ngs 5

不。

如果您向 提供谓词wait,则无需在调用该函数之前自行检查它。

引用的 cppreference.com 文章在这方面可以说是误导性的(和/或错误的),尽管该文章wait在基于代码的示例中是关于金钱的,这与标准中给出的定义相同:

while (!pred())
   wait(lock);
Run Code Online (Sandbox Code Playgroud)

该页面上的第二组要点似乎是从稍微更高层次的角度来解决问题的,没有考虑到调用wait()本身确实会为您执行检查pred()(如果您提供了一个检查)。

wait()这可能是因为它的重载不需要a pred,并且通常不需要条件变量知道您正在测试的条件:很可能使用它来检查某些“外部”条件。但是,如今,我们通常只是将 lambda 推入其中pred并完成它,所以......

几周前,我遇到了这种不一致的情况(此处之前的讨论),但尚未为本文提出更好的措辞。