std::condition_variable::notify_all
提供: cppreference.com
void notify_all() noexcept; |
(C++11以上) | |
現在 *this で待機しているすべてのスレッドのブロックを解除します。
引数
(なし)
戻り値
(なし)
ノート
notify_one()/notify_all() および wait()/wait_for()/wait_until() の3つのアトミック部分 (unlock+wait、wakeup、lock) 各々の効果は、アトミック変数の変更順序として考えることができる単一の全順序で行われます。 この順序は個々の条件変数に固有です。 これにより、例えば notify_one() が遅延され、 notify_one() の呼び出しの後に待機を開始したスレッドをブロック解除することは、ありえなくなります。
通知スレッドは、待機中のスレッドが保持しているものと同じミューテックスのロックを保持している必要はありません。 実際、それは効率の悪いことです。 通知されたスレッドは、通知スレッドがロックを解放するのを待って、すぐに再びブロックされます。
例
Run this code
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
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
関連項目
| 待機中のスレッドひとつに通知します (パブリックメンバ関数) | |
cnd_broadcast の C言語リファレンス
|