◐ Shell
clean mode source ↗

std::latch - cppreference.com

来自cppreference.com

(C++20 起)

latch 类是一种 std::ptrdiff_t 类型的向下计数器,它能用于同步线程。在创建时初始化计数器的值。线程可能在闩上阻塞直至计数器减少到零。没有可能增加或重置计数器,这使得 latch 成为一种单次使用的屏障。

同时调用 latch 的成员函数,除了析构函数,不引入数据竞争。

数据成员

成员名 定义
std::ptrdiff_t counter 内部计数器
(仅用于阐述的成员对象*)

成员函数

构造 latch
(公开成员函数) [编辑]
析构 latch
(公开成员函数) [编辑]

operator=

[弃置]

latch 不可赋值
(公开成员函数)
以不阻塞的方式减少计数器
(公开成员函数) [编辑]
测试内部计数器是否等于零
(公开成员函数) [编辑]
阻塞直至计数器抵达零
(公开成员函数) [编辑]
减少计数器并阻塞直至它抵达零
(公开成员函数) [编辑]
常量

[静态]

实现所支持的计数器最大值
(公开静态成员函数) [编辑]

注解

功能特性测试 标准 功能特性
__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{"未工作"};
    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 + " 已工作";
        work_done.count_down();
        start_clean_up.wait();
        my_job.product = my_job.name + " 已清理";
    };

    std::cout << "工作启动... ";
    for (auto& job : jobs)
        job.action = std::thread{work, std::ref(job)};

    work_done.wait();
    std::cout << "完成:\n";
    for (auto const& job : jobs)
        std::cout << "  " << job.product << '\n';

    std::cout << "清理工作线程... ";
    start_clean_up.count_down();
    for (auto& job : jobs)
        job.action.join();

    std::cout << "完成:\n";
    for (auto const& job : jobs)
        std::cout << "  " << job.product << '\n';
}

输出:

工作启动... 完成:
  Annika 已工作
  Buru 已工作
  Chuck 已工作
清理工作线程... 完成:
  Annika 已清理
  Buru 已清理
  Chuck 已清理

参阅