在while循环内使用std :: condition_variable :: wait是否正确?

Boa*_*ges 2 c++ condition-variable thread-safety c++11

我目前正在研究std :: condition_variable。在while循环内使用std :: condition_variable :: wait()完全不依赖std :: condition_variable :: notify()是否正确?

每个std :: condition_variable :: wait()都应强制具有std :: condition_variable :: notify()吗?

Pet*_*ker 5

您可以循环使用它,并且依赖notify()

问题是允许条件变量“虚假地”唤醒,即不发出信号。这使实现起来更容易,但是它要求您检查自己是否确实在您认为的位置。因此,您编写了一个循环:

std::unique_lock<std::mutex> lk(some_mutex);
while (condition_not_satisfied())
    cond_var.wait(lk);
Run Code Online (Sandbox Code Playgroud)

其中some_mutex提供了条件中使用的变量的关键区域。

或者,正如Slava指出的那样,您可以使用谓词版本:

std::unique_lock<std::mutex> lk(some_mutex);
cond_var.wait(lk, some_callable_object_that_checks_the_predicate);
Run Code Online (Sandbox Code Playgroud)

(我从不喜欢这种形式,所以我往往会忘记它)

  • “所以您写一个循环”或您使用谓词版本 (2认同)
  • 还有另一个更好的循环原因:在多用户应用程序中,一个线程可能由于notify_all而醒来,并发现某个_other_线程已经处理了该事件。在这种情况下,您通常希望第一个线程返回并等待下一个事件。即使不是虚假唤醒,始终循环也是个好习惯,这样一来,其他一些阅读您的代码的程序员就不必花费时间试图弄清楚为什么在您的特定应用程序中可以_not_编写它。 (2认同)