C++ 库 - <latch>



C++20 中的<latch> 头文件是一个一次性使用的同步原语,它确保一组线程等待直到满足预定义的条件。一旦满足此条件,所有等待的线程都将被处理。与 barrier 不同,latch 使用后不会重置。

<latch> 使用给定的计数进行构造,每个线程调用 count_down() 函数来减少内部计数器。当计数器达到零时,所有等待 latch 的线程都将被释放。如果线程在 latch 准备好之前尝试调用 wait(),它将阻塞直到计数器达到零。

包含 <latch> 头文件

要在您的 C++ 程序中包含 <latch> 头文件,您可以使用以下语法。

#include <latch>

<latch> 头文件的函数

以下是 <latch> 头文件中的所有函数列表。

序号 函数及描述
1 count_down

将内部计数器递减 1。

2 try_wait

测试内部计数器是否等于零。

3 wait

阻塞直到计数器达到零。

4 arrive_and_wait

递减计数器并阻塞直到它达到零。

5 max

返回实现支持的内部计数器的最大值。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

带多个计数的 Latch

在下面的示例中,我们将使用 latch 用于两个“A”。每个“A”在完成时递减 latch,主线程等待直到两个“A”都完成然后打印一条消息。

#include <iostream> #include <thread> #include <latch> void a(int b, std::latch & latch) { std::cout << "A" << b << " Is Starting..\n"; std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "A" << b << " Finished Work.!\n"; latch.count_down(); } int main() { std::latch latch(2); std::thread x1(a, 1, std::ref(latch)); std::thread x2(a, 2, std::ref(latch)); latch.wait(); std::cout << "Work Is Done..\n"; x1.join(); x2.join(); return 0; }

输出

以上代码的输出如下:

A1 Is Starting..
A2 Is Starting..
A1 Finished Work.!
A2 Finished Work.!
Work Is Done..
广告