std::latch
来自 cppreference.cn
定义于头文件 <latch> |
||
class latch; |
(自 C++20 起) | |
latch
类是一个类型为 std::ptrdiff_t 的向下计数器,可用于同步线程。计数器的值在创建时初始化。线程可以在闩锁上阻塞,直到计数器递减至零。无法增加或重置计数器,这使得闩锁成为一次性屏障。
并发调用 std::latch
的成员函数(析构函数除外)不会引入数据竞争。
目录 |
[编辑] 数据成员
名称 | 定义 |
std::ptrdiff_t counter |
内部计数器 (仅供演示的成员对象*) |
[编辑] 成员函数
构造一个 latch (公共成员函数) | |
销毁 latch (公共成员函数) | |
operator= [已删除] |
latch 不可赋值(公共成员函数) |
以非阻塞方式递减计数器 (公共成员函数) | |
测试内部计数器是否等于零 (公共成员函数) | |
阻塞直到计数器达到零 (公共成员函数) | |
递减计数器并阻塞直到其达到零 (公共成员函数) | |
常量 | |
[静态] |
实现支持的计数器的最大值 (公共静态成员函数) |
[编辑] 注释
特性测试宏 | 值 | Std | 特性 |
---|---|---|---|
__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) |
可重用线程屏障 (类模板) |