std::jthread::get_stop_token

来自cppreference.com
< cpp‎ | thread‎ | jthread
 
 
并发支持库
线程
(C++11)
(C++20)
this_thread 命名空间
(C++11)
(C++11)
(C++11)
协作式取消
互斥
通用锁管理
(C++11)
(C++11)
(C++11)
(C++11)
条件变量
(C++11)
信号量
闩与屏障
(C++20)
(C++20)
未来体
(C++11)
(C++11)
(C++11)
安全回收
风险指针
原子类型
(C++11)
(C++20)
原子类型的初始化
(C++11)(C++20 弃用)
(C++11)(C++20 弃用)
内存定序
(C++11)(C++26 弃用)
原子操作的自由函数
原子标志的自由函数
 
 
std::stop_token get_stop_token()constnoexcept;
(C++20 起)

返回 std::stop_token,它与 jthread 对象内部保有的同一共享停止状态关联。

[编辑]参数

(无)

[编辑]返回值

jthread 对象内部保有的共享停止状态关联的 std::stop_token 类型的值。

[编辑]示例

#include <chrono>#include <condition_variable>#include <iostream>#include <mutex>#include <string_view>#include <thread>   usingnamespace std::chrono_literals;   void print(std::string_view name, conststd::stop_token& token){std::cout<< name <<": stop_possible = "<< token.stop_possible();std::cout<<", stop_requested = "<< token.stop_requested()<<'\n';}   void finite_sleepy(std::stop_token stoken){for(int i =10; i;--i){std::this_thread::sleep_for(300ms);if(stoken.stop_requested()){std::cout<<" 困倦工人已被请求停止\n";return;}   std::cout<<" 困倦工人回去睡觉\n";}}   void infinite_sleepy(){for(int i =5; i;--i){std::this_thread::sleep_for(300ms);std::cout<<" 按要求持续运行\n";}}     int main(){std::cout<<std::boolalpha;   // 监听停止请求的工作线程std::jthread stop_worker(finite_sleepy);   // 仅在完成时停止的工作线程std::jthread inf_worker(infinite_sleepy);   std::stop_token def_token;std::stop_token stop_token = stop_worker.get_stop_token();std::stop_token inf_token = inf_worker.get_stop_token(); print("def_token ", def_token); print("stop_token", stop_token); print("inf_token ", inf_token);   std::cout<<"\n请求并接合 stop_worker:\n"; stop_worker.request_stop(); stop_worker.join();   std::cout<<"\n请求并接合 inf_worker:\n"; inf_worker.request_stop(); inf_worker.join();std::cout<<'\n';   print("def_token ", def_token); print("stop_token", stop_token); print("inf_token ", inf_token);}

可能的输出:

def_token : stop_possible = false, stop_requested = false stop_token: stop_possible = true, stop_requested = false inf_token : stop_possible = true, stop_requested = false   请求并接合: 按要求持续运行 困倦工人已被请求停止   请求并接合: 按要求持续运行 按要求持续运行 按要求持续运行 按要求持续运行   def_token : stop_possible = false, stop_requested = false stop_token: stop_possible = true, stop_requested = true inf_token : stop_possible = true, stop_requested = true
close