std::latch
來自 cppreference.com
定義於標頭檔案 <latch> |
||
class latch; |
(C++20 起) | |
latch
類是一個型別為 std::ptrdiff_t 的向下計數器,可用於同步執行緒。計數器的值在建立時初始化。執行緒可能會在計數器減到零之前阻塞在 latch 上。無法增加或重置計數器,這使得 latch 成為一次性屏障。
std::latch
的成員函式的併發呼叫,除了解構函式,不會引入資料競爭。
目錄 |
[編輯] 資料成員
名稱 | 定義 |
std::ptrdiff_t counter |
內部計數器 (僅用於闡釋的成員物件*) |
[編輯] 成員函式
構造 latch (public member function) | |
銷燬 latch (public member function) | |
operator= [已刪除] |
latch 不可賦值(公開成員函式) |
以非阻塞方式遞減計數器 (public member function) | |
測試內部計數器是否為零 (public member function) | |
阻塞直到計數器達到零 (public member function) | |
遞減計數器並阻塞直到它達到零 (public member function) | |
常量 | |
[靜態] |
實現支援的計數器的最大值 (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) |
可重用執行緒屏障 (class template) |