Namespaces
Variants

std:: latch

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
latch
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
定义于头文件 <latch>
class latch ;
(C++20 起)

latch 类是一个类型为 std::ptrdiff_t 的递减计数器,可用于线程同步。计数器的值在创建时初始化。线程可以在锁存器上阻塞,直到计数器递减至零。该计数器无法增加或重置,这使得锁存器成为一次性屏障。

除了析构函数外,对 std::latch 成员函数的并发调用不会引入数据竞争。

目录

数据成员

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

成员函数

构造 latch
(公开成员函数)
销毁 latch
(公开成员函数)
operator=
[deleted]
latch 不可赋值
(公开成员函数)
以非阻塞方式递减计数器
(公开成员函数)
检查内部计数器是否等于零
(公开成员函数)
阻塞直至计数器归零
(公开成员函数)
递减计数器并阻塞直至其归零
(公开成员函数)
常量
[static]
实现所支持的最大计数器值
(公开静态成员函数)

注释

功能测试 标准 功能
__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)
可复用线程屏障
(类模板)