[英]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.我正在编写一个 c++ 多线程程序,其中有多个线程等待通知。
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.本来以为notify的顺序就是线程构造的顺序。 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.实际上,实现可能只使用任何最有效的方法来实现
std::condition_variable
,操作系统对线程的管理的不确定性也会影响它。
So don't write any code that relies in any way on which thread will be woken up.所以不要编写任何依赖于哪个线程将被唤醒的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.