简体   繁体   中英

If there are many threads are waiting to be notify, which one does the std::condition_variable::notify_one() function notify?

I am writing a c++ multithread program, which have more than one thread wait to be notify.

  std::mutex mutex;

  std::condition_variable cv;

  bool is_prepared = false;
  bool is_fornt_left_finished = false;
  bool is_fornt_right_finished = false;
  bool is_back_left_finished = false;
thread t1(&Underpan::FrontLeft, this), t2(&Underpan::FrontRight, this),
        t3(&Underpan::BackLeft, this), t4(&Underpan::BackRight, this);
    is_prepared = true;
    t1.join();
    t2.join();
    t3.join();
    t4.join();
    cv.notify_one();  // fail
    // cv.notify_all(); // success

I originally thought that the order of notify is the order of thread construction. But in actual operation, the program can be successfully run occasionally, and the program will be blocked occasionally.

I've checked the official documents and didn't explain this part of the details.

官方文档

官方文档

Whether the sequence is unpredictable or not?

It is unspecified which thread will be woken up. There doesn't need to be any particular rule to it. There doesn't need to be any "sequence" either. It could just always keep waking up the same thread (as long as it is always waiting when the notification happens) and it could also randomly wake up a different thread.

Of course the particular standard library implementation may make some guarantee, but I don't think it is likely that it will. Practically the implementation will likely just use whatever approach is the most efficient for implementing std::condition_variable and uncertainty from the operating system's management of the threads will also play into it.

So don't write any code that relies in any way on which thread will be woken up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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