简体   繁体   English

condition_variable的while循环

[英]while loop for condition_variable

In the following example, I don't understand the purpose of ready . 在以下示例中,我不了解ready的目的。 What is difference with or without using ready in this example? 在此示例中,使用或不使用ready有什么区别?

#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id (int id) {
  std::unique_lock<std::mutex> lck(mtx);
  while (!ready) cv.wait(lck);
  // ...
  std::cout << "thread " << id << '\n';
}

void go() {
  std::unique_lock<std::mutex> lck(mtx);
  ready = true;
  cv.notify_all();
}

int main ()
{
  std::thread threads[10];
  // spawn 10 threads:
  for (int i=0; i<10; ++i)
    threads[i] = std::thread(print_id,i);

  std::cout << "10 threads ready to race...\n";
  go();                       // go!

  for (auto& th : threads) th.join();

  return 0;
}

The reason is that cv.wait(lck); 原因是cv.wait(lck); can return before the notify_all call has been made, due to things called "spurious wakeups". 由于称为“虚假唤醒”的事件,可以在进行 notify_all调用之前返回。 You can see Spurious wakeups explanation sounds like a bug that just isn't worth fixing, is that right? 您会看到“ 虚假唤醒”的解释听起来像是一个不值得修复的错误,对吗? for some more information about the reasons for this. 有关此原因的更多信息。

Thus, the waiting/notifying threads use an additional predicate ( ready in this case) to signal whether the condition was signaled or whether the condition awoke due to a spurious wakeup. 因此,等待/通知线程使用一个附加的谓词(在这种情况下ready )来发信号通知该条件是否已发出信号或该条件是否由于虚假唤醒而唤醒。

When it is not ready ( ready is false) you will block thread/threads until you will call one/all of them and let them do their job. 如果没有readyready为false),您将阻塞一个或多个线程,直到调用其中一个或所有线程,然后让它们完成工作为止。 However when ready is true, you will not block any threads. 但是,当ready为true时,您将不会阻塞任何线程。 It is important, because without ready flag you might block thread which should be executing and therefore there will be no information to let it run again(when you block thread you have to notify it, otherwise it will wait forever) 这很重要,因为没有ready标志,您可能会阻塞应执行的线程,因此将没有信息让它再次运行(当您阻塞线程时,您必须通知它,否则它将永远等待)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM