std::latch
来自cppreference.com
在标头 <latch> 定义
|
||
class latch; |
(C++20 起) | |
latch
是 std::ptrdiff_t 类型的向下计数器,它能用于同步线程。在创建时初始化计数器的值。
线程可能在 latch
上阻塞直至计数器减少到零。没有可能增加或重置计数器,这使得 latch
为单次使用的屏障。
同时调用 latch
的成员函数,除了析构函数,不引入数据竞争。
不同于 std::barrier ,参与线程能减少 std::latch
多于一次。
成员函数
构造 latch (公开成员函数) | |
析构 latch (公开成员函数) | |
operator= [被删除] |
latch 不可赋值 (公开成员函数) |
以不阻塞的方式减少计数器 (公开成员函数) | |
测试内部计数器是否等于零 (公开成员函数) | |
阻塞直至计数器抵达零 (公开成员函数) | |
减少计数器并阻塞直至它抵达零 (公开成员函数) | |
常量 | |
[静态] |
实现所支持的计数器最大值 (公开静态成员函数) |
注解
功能特性测试宏 | 值 | 标准 | 备注 |
---|---|---|---|
__cpp_lib_latch |
201907L | (C++20) | std::latch |
示例
运行此代码
#include <functional> #include <iostream> #include <latch> #include <string> #include <thread> int main() { struct job { const std::string name; std::string product{"not worked"}; std::thread action{}; } 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 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 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 starting... done: annika worked buru worked chuck worked Workers cleaning up... done: annika cleaned buru cleaned chuck cleaned
参阅
(C++20) |
可复用的线程屏障 (类模板) |