std::stop_token
From cppreference.com
| ヘッダ <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 の中断可能な待機関数に渡すことができ、停止が要求された場合に条件変数の待機を中断します。
目次 |
[編集] メンバエイリアステンプレート
| 型 | 定義 |
| callback_type<Callback> (C++26以降) | std::stop_callback<Callback> |
[編集] メンバ関数
新しい stop_token オブジェクトを構築する(public メンバ関数) | |
stop_token オブジェクトを破棄する(public メンバ関数) | |
stop_token オブジェクトを代入する(public メンバ関数) | |
変更 | |
2つの stop_token オブジェクトをスワップする(public メンバ関数) | |
監視 | |
| 関連付けられた停止状態が停止を要求されたかどうかをチェックする (public メンバ関数) | |
| 関連付けられた停止状態が停止を要求できるかどうかをチェックする (public メンバ関数) | |
[編集] 非メンバ関数
| (C++20) |
2つの std::stop_token オブジェクトを比較する(関数) |
| (C++20) |
std::swap アルゴリズムを特殊化する (関数) |
[編集] 備考
stop_token オブジェクトは通常、独立して構築されるのではなく、std::jthread または std::stop_source から取得されます。これにより、std::jthread または std::stop_source と同じ関連停止状態を共有します。
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_lib_jthread |
201911L |
(C++20) | 停止トークンと結合可能なスレッド |
[編集] 例
このコードを実行
#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