std::stop_token:: stop_requested
From cppreference.net
<
cpp
|
thread
|
stop token
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::stop_token
| Member functions | ||||
| Modifiers | ||||
| Observers | ||||
|
stop_token::stop_requested
|
||||
| Non-member functions | ||||
|
bool
stop_requested
(
)
const
noexcept
;
|
(C++20 起) | |
检查
stop_token
对象是否具有关联的停止状态且该状态已收到停止请求。默认构造的
stop_token
没有关联的停止状态,因此不会收到停止请求。
参数
(无)
返回值
当 stop_token 对象具有关联停止状态且已收到停止请求时返回 true ,否则返回 false 。
示例
运行此代码
#include <chrono> #include <condition_variable> #include <iostream> #include <mutex> #include <string_view> #include <thread> using namespace std::chrono_literals; int main() { std::cout << std::boolalpha; auto print = [](std::string_view name, const std::stop_token& token) { std::cout << name << ": stop_possible = " << token.stop_possible(); std::cout << ", stop_requested = " << token.stop_requested() << '\n'; }; // 一个监听停止请求的工作线程 auto stop_worker = std::jthread([](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"; } }); // 一个仅在完成时停止的工作线程 auto inf_worker = std::jthread([]() { for (int i = 5; i; --i) { std::this_thread::sleep_for(300ms); std::cout << " 按需运行任意时长\n"; } }); 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 请求并加入stop_worker: 按需运行任意时长 睡眠工作线程收到停止请求 请求并加入inf_worker: 按需运行任意时长 按需运行任意时长 按需运行任意时长 按需运行任意时长 def_token : stop_possible = false, stop_requested = false stop_token: stop_possible = true, stop_requested = true inf_token : stop_possible = true, stop_requested = true