std::latch
来自 cppreference.com
定义在头文件 <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) |
可重用线程屏障 (类模板) |