std::stop_token::stop_possible
From cppreference.com
< cpp | スレッド | stop token
| bool stop_possible() const noexcept; |
(C++20以降) | |
stop_token オブジェクトに、停止要求が既に発行されたか、または関連する std::stop_source オブジェクトが存在する停止状態が関連付けられているかどうかをチェックします。
デフォルト構築された stop_token は、関連付けられた停止状態を持たないため、停止することはできません。関連付けられた停止状態に std::stop_source オブジェクトが存在しない場合、そのような要求がまだ行われていない場合も停止できません。
目次 |
[編集] パラメータ
(なし)
[編集] 戻り値
stop_token オブジェクトに関連付けられた停止状態がない場合、またはまだ停止要求を受け取っておらず、関連付けられた std::stop_source オブジェクトが存在しない場合は false。それ以外の場合は true。
[編集] 注記
stop_token オブジェクトに関連付けられた停止状態があり、既に停止要求が行われている場合でも、この関数は true を返します。
stop_token オブジェクトが std::jthread から関連付けられた停止状態を持っている場合(例えば、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