命名空间
变体
操作

std::latch

来自 cppreference.cn
< cpp‎ | thread
 
 
并发支持库
线程
(C++11)
(C++20)
this_thread 命名空间
(C++11)
(C++11)
(C++11)
协同取消
互斥
(C++11)
通用锁管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
条件变量
(C++11)
信号量
门闩和屏障
latch
(C++20)
(C++20)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危险指针
原子类型
(C++11)
(C++20)
原子类型的初始化
(C++11)(C++20 中已弃用)
(C++11)(C++20 中已弃用)
内存排序
(C++11)(C++26 中已弃用)
原子操作的自由函数
原子标志的自由函数
 
 
定义于头文件 <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) [编辑]