std:: latch
From cppreference.net
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::latch
| Member functions | ||||
| Constants | ||||
|
定義ヘッダ
<latch>
|
||
|
class
latch
;
|
(C++20以降) | |
latch
クラスは、スレッドの同期に使用できる
std::ptrdiff_t
型の下降カウンタです。カウンタの値は作成時に初期化されます。スレッドはカウンタがゼロにデクリメントされるまでラッチでブロックできます。カウンタを増加またはリセットする機能はないため、ラッチは単回使用のバリアとなります。
std::latch
のメンバ関数の同時呼び出しは、デストラクタを除いて、データ競合を引き起こしません。
目次 |
データメンバ
| 名前 | 定義 |
std::ptrdiff_t
counter
|
内部カウンター
( 説明専用メンバーオブジェクト* ) |
メンバー関数
latch
を構築する
(public member function) |
|
latch
を破棄する
(public member function) |
|
|
operator=
[deleted]
|
latch
は代入不可
(public member function) |
|
非ブロッキング方式でカウンタをデクリメントする
(public member function) |
|
|
内部カウンタがゼロかどうかをテストする
(public member function) |
|
|
カウンタがゼロに達するまでブロックする
(public member function) |
|
|
カウンタをデクリメントし、ゼロに達するまでブロックする
(public member function) |
|
定数 |
|
|
[static]
|
実装でサポートされるカウンタの最大値
(public static member function) |
注記
| 機能テスト マクロ | 値 | 標準 | 機能 |
|---|---|---|---|
__cpp_lib_latch
|
201907L
|
(C++20) |
std::latch
|
例
このコードを実行
#include <functional> #include <iostream> #include <latch> #include <string> #include <thread> struct Job { const std::string name; std::string product{"not worked"}; std::thread action{}; }; int main() { Job jobs[]{{"Annika"}, {"Buru"}, {"Chuck"}}; std::latch work_done{std::size(jobs)}; std::latch start_clean_up{1}; auto work = [&](Job& my_job) { my_job.product = my_job.name + " worked"; work_done.count_down(); start_clean_up.wait(); my_job.product = my_job.name + " cleaned"; }; std::cout << "Work is starting... "; for (auto& job : jobs) job.action = std::thread{work, std::ref(job)}; work_done.wait(); std::cout << "done:\n"; for (auto const& job : jobs) std::cout << " " << job.product << '\n'; std::cout << "Workers are cleaning up... "; start_clean_up.count_down(); for (auto& job : jobs) job.action.join(); std::cout << "done:\n"; for (auto const& job : jobs) std::cout << " " << job.product << '\n'; }
出力:
Work is starting... done: Annika worked Buru worked Chuck worked Workers are cleaning up... done: Annika cleaned Buru cleaned Chuck cleaned
関連項目
|
(C++20)
|
再利用可能なスレッドバリア
(クラステンプレート) |