簡體   English   中英

如果有很多線程在等待通知,std::condition_variable::notify_one() function 通知哪一個?

[英]If there are many threads are waiting to be notify, which one does the std::condition_variable::notify_one() function 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

本來以為notify的順序就是線程構造的順序。 但是在實際運行中,程序偶爾能成功運行,也偶爾會卡住。

我查了官方文檔,沒有解釋這部分細節。

官方文檔

官方文檔

順序是否不可預測?

未指定將喚醒哪個線程。 它不需要任何特定的規則。 也不需要任何“順序”。 它可以一直喚醒同一個線程(只要它在通知發生時一直在等待),也可以隨機喚醒一個不同的線程。

當然,特定的標准庫實現可能會做出一些保證,但我認為這不太可能。 實際上,實現可能只使用任何最有效的方法來實現std::condition_variable ,操作系統對線程的管理的不確定性也會影響它。

所以不要編寫任何依賴於哪個線程將被喚醒的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM