C++线程中的notify_one()唤醒多个线程

Red*_*001 3 c++ multithreading conditional-statements

您好,我有以下代码:

// condition_variable example
#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> lock(mtx);
  while (!ready) cv.wait(lock);
  // ...
  std::cout << "thread " << id << std::endl;
}

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

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..." << std::endl;
  go();                       // go!

  for (auto& th : threads) th.join();
  std::cout << "Finished!" << std::endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

10 threads ready to race...
thread 9
thread 0
Run Code Online (Sandbox Code Playgroud)

我的期望是通过调用notify_one(),只会通知一个线程并且我会陷入死锁。但是在这种情况下,在重新解决死锁之前通知了两个线程。我在这里缺少什么?谢谢

Kan*_*ane 5

当您调用go(). 那么这可能会发生:

  1. 九个线程正在运行并等待条件变量。
  2. 你叫go()这台readytrue并通知线程为零。
  3. 第十个线程启动,它看到的readytrue并且不等待条件变量。