C++ 库 - <stop_token>



C++20 中的<stop_token> 头文件引入了一种取消线程和异步操作的机制。它与 `std::stop_source` 配合使用,`std::stop_source` 负责生成停止请求。

这些用于实现响应式系统,该系统可以停止操作,而无需强制终止或复杂的信号机制。

包含 <stop_token> 头文件

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

#include <stop_token>

<stop_token> 头文件的函数

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

序号 函数及描述
1 operator=

它赋值 `stop_token` 对象。

2 swap

它交换两个 `stop_token` 对象。

3 stop_requested

它检查关联的停止状态是否已请求停止。

4 stop_possible

它检查关联的停止状态是否可以请求停止。

5 get_token

它返回关联停止状态的 `stop_token`。

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

使用停止令牌的多线程

在下面的示例中,我们将使用 `std::stop_source` 来控制多个线程。

#include <iostream> #include <thread> #include <stop_token> #include <chrono> void a(int id, std::stop_token b) { while (!b.stop_requested()) { std::cout << "A " << id << " Is Working.." << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(600)); } std::cout << "A " << id << " Is Cancelled.." << std::endl; } int main() { std::stop_source x; std::thread x1(a, 1, x.get_token()); std::thread x2(a, 2, x.get_token()); std::this_thread::sleep_for(std::chrono::seconds(2)); x.request_stop(); x1.join(); x2.join(); return 0; }

输出

以上代码的输出如下:

A 2 Is Working..
A 1 Is Working..
A 2 Is Working..
A 1 Is Working..
A 2 Is Working..
A 1 Is Working..
A 2 Is Working..
A 1 Is Working..
A 2 Is Cancelled..
A 1 Is Cancelled..
广告