std::stop_token
來自 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 的可中斷等待函式,以便在請求停止時中斷條件變數的等待。
目錄 |
[edit] 成員別名模板
型別 | 定義 |
callback_type<Callback> (從 C++26 開始) | std::stop_callback<Callback> |
[edit] 成員函式
構造新的 stop_token 物件(public member function) | |
銷燬 stop_token 物件(public member function) | |
賦值 stop_token 物件(public member function) | |
修改器 | |
交換兩個 stop_token 物件(public member function) | |
觀察器 | |
檢查關聯的停止狀態是否已被請求停止 (public member function) | |
檢查關聯的停止狀態是否可以被請求停止 (public member function) |
[edit] 非成員函式
(C++20) |
比較兩個 std::stop_token 物件(function) |
(C++20) |
特化 std::swap 演算法 (function) |
[edit] 備註
stop_token
物件通常不是獨立構造的,而是從 std::jthread 或 std::stop_source 檢索的。這使得它與 std::jthread 或 std::stop_source 共享相同的關聯停止狀態。
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_jthread |
201911L |
(C++20) | 停止令牌 和 連線執行緒 |
[edit] 示例
執行此程式碼
#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