std::stop_token::stop_possible
来自 cppreference.com
< cpp | thread | stop token
bool stop_possible() const noexcept; |
(自 C++20 起) | |
检查 stop_token
对象是否具有关联的停止状态,以及该状态是否已请求停止或是否具有关联的 std::stop_source 对象。
默认构造的 stop_token 没有关联的停止状态,因此无法停止;对于没有 std::stop_source 对象的关联停止状态,如果尚未发出请求,也无法停止。
内容 |
[编辑] 参数
(无)
[编辑] 返回值
false 如果 stop_token
对象没有关联的停止状态,或者它还没有收到停止请求,并且没有关联的 std::stop_source 对象;否则为 true。
[编辑] 注释
如果 stop_token
对象具有关联的停止状态,并且已经发出停止请求,则此函数仍返回 true。
如果 stop_token
对象具有来自 std::jthread 的关联停止状态 - 例如,stop_token
是通过在 std::jthread 对象上调用 get_stop_token() 获取的 - 那么此函数始终返回 true。一个 std::jthread 始终具有一个内部 std::stop_source 对象,即使线程的调用函数没有检查它。
[编辑] 示例
运行此代码
#include <chrono> #include <condition_variable> #include <format> #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 << std::format("{}: stop_possible = {:s}, stop_requested = {:s}\n", name, token.stop_possible(), token.stop_requested() ); }; // A worker thread that will listen to stop requests 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 << " Sleepy worker is requested to stop\n"; return; } std::cout << " Sleepy worker goes back to sleep\n"; } }); // A worker thread that will only stop when completed auto inf_worker = std::jthread([]() { for (int i = 5; i; --i) { std::this_thread::sleep_for(300ms); std::cout << " Run as long as we want\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 << "\nRequest and join stop_worker:\n"; stop_worker.request_stop(); stop_worker.join(); std::cout << "\nRequest and join 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 Request and join stop_worker: Run as long as we want Sleepy worker is requested to stop Request and join inf_worker: Run as long as we want Run as long as we want Run as long as we want Run as long as we want def_token : stop_possible = false, stop_requested = false stop_token: stop_possible = true, stop_requested = true inf_token : stop_possible = true, stop_requested = true