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‘v e checked the official documents and didn't explain this part of the details.
Whether the sequence is unpredictable or not?
CodePudding user response:
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.