std::stop_token
来自 cppreference.cn
定义于头文件 <stop_token> |
||
class stop_token; |
(自 C++20 起) | |
stop_token
类提供了检查是否已发出或可以发出停止请求的方法,用于其关联的 std::stop_source 对象。它本质上是关联停止状态的线程安全“视图”。
stop_token
也可以传递给 std::stop_callback 的构造函数,这样,如果请求 stop_token
的关联 std::stop_source 停止,则将调用回调。并且 stop_token
可以传递给 std::condition_variable_any 的可中断等待函数,以在请求停止时中断条件变量的等待。
内容 |
[edit] 成员别名模板
类型 | 定义 |
callback_type<Callback> (自 C++26 起) | std::stop_callback<Callback> |
[edit] 成员函数
构造新的 stop_token 对象(公有成员函数) | |
析构 stop_token 对象(公有成员函数) | |
赋值 stop_token 对象(公有成员函数) | |
修饰符 | |
交换两个 stop_token 对象(公有成员函数) | |
观察器 | |
检查是否已请求关联的停止状态停止 (公有成员函数) | |
检查是否可以请求关联的停止状态停止 (公有成员函数) |
[edit] 非成员函数
(C++20) |
比较两个 std::stop_token 对象(函数) |
(C++20) |
特化 std::swap 算法 (函数) |
[edit] 注解
stop_token
对象通常不是独立构造的,而是从 std::jthread 或 std::stop_source 检索的。这使其与 std::jthread 或 std::stop_source 共享相同的关联停止状态。
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_jthread |
201911L |
(C++20) | 停止令牌 和 joining thread |
[edit] 示例
运行此代码
#include <iostream> #include <thread> using namespace std::literals::chrono_literals; void f(std::stop_token stop_token, int value) { while (!stop_token.stop_requested()) { std::cout << value++ << ' ' << std::flush; std::this_thread::sleep_for(200ms); } std::cout << std::endl; } int main() { std::jthread thread(f, 5); // prints 5 6 7 8... for approximately 3 seconds std::this_thread::sleep_for(3s); // The destructor of jthread calls request_stop() and join(). }
可能的输出
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19