我正在撰寫一個 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
本來以為notify的順序就是執行緒構造的順序。但是在實際運行中,程式偶爾能成功運行,也偶爾會卡住。
我查了官方檔案,沒有解釋這部分細節。


順序是否不可預測?
uj5u.com熱心網友回復:
未指定將喚醒哪個執行緒。它不需要任何特定的規則。也不需要任何“順序”。它可以一直喚醒同一個執行緒(只要它在通知發生時一直在等待),也可以隨機喚醒一個不同的執行緒。
當然,特定的標準庫實作可能會做出一些保證,但我認為這不太可能。實際上,實作可能只使用最有效的實作方法std::condition_variable,作業系統執行緒管理的不確定性也會影響它。
所以不要撰寫任何依賴于哪個執行緒將被喚醒的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/537173.html
