std::condition_variable::notify_all
From cppreference.com
< cpp | thread | condition variable
| void notify_all() noexcept; |
(C++11以降) | |
現在 *this を待機しているすべてのスレッドを解除します。
目次 |
[編集] パラメータ
(なし)
[編集] 戻り値
(なし)
[編集] 注釈
notify_one()/notify_all() と、wait()/wait_for()/wait_until() の 3 つのアトミック部分(アンロック+待機、ウェイクアップ、ロック)の効果は、単一の全順序で発生します。これは、アトミック変数の一連の 変更順序 と見なすことができます。この順序は、この個別の条件変数に固有のものです。これにより、例えば、notify_one() の呼び出しが行われた直後に待機を開始したスレッドを解除するために notify_one() が遅延することは不可能になります。
通知するスレッドは、待機中のスレッドが保持しているミューテックスと同じミューテックスのロックを保持する必要はありません。そうすることは、通知されたスレッドがすぐに再度ブロックされ、通知したスレッドがロックを解放するのを待つことになるため、性能低下の原因となる可能性があります。ただし、一部の実装ではこのパターンを認識し、ロック下で通知されたスレッドを起こそうとはしません。
[編集] 例
このコードを実行
#include <chrono> #include <condition_variable> #include <iostream> #include <thread> std::condition_variable cv; std::mutex cv_m; // This mutex is used for three purposes: // 1) to synchronize accesses to i // 2) to synchronize accesses to std::cerr // 3) for the condition variable cv int i = 0; void waits() { std::unique_lock<std::mutex> lk(cv_m); std::cerr << "Waiting... \n"; cv.wait(lk, []{ return i == 1; }); std::cerr << "...finished waiting. i == 1\n"; } void signals() { std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); std::cerr << "Notifying...\n"; } cv.notify_all(); std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); i = 1; std::cerr << "Notifying again...\n"; } cv.notify_all(); } int main() { std::thread t1(waits), t2(waits), t3(waits), t4(signals); t1.join(); t2.join(); t3.join(); t4.join(); }
実行結果の例
Waiting... Waiting... Waiting... Notifying... Notifying again... ...finished waiting. i == 1 ...finished waiting. i == 1 ...finished waiting. i == 1
[編集] 関連項目
| 待機中のスレッドを1つ通知します。 (public member function) | |
| C ドキュメント for cnd_broadcast
| |