名稱空間
變體
操作

std::stop_token

來自 cppreference.com
< cpp‎ | thread
 
 
併發支援庫
執行緒
(C++11)
(C++20)
this_thread 名稱空間
(C++11)
(C++11)
(C++11)
協同取消
stop_token
(C++20)
互斥
(C++11)
通用鎖管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
條件變數
(C++11)
訊號量
門閂和屏障
(C++20)
(C++20)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危險指標
原子型別
(C++11)
(C++20)
原子型別的初始化
(C++11)(C++20 中已棄用)
(C++11)(C++20 中已棄用)
記憶體排序
(C++11)(C++26 中已棄用)
原子操作的自由函式
原子標誌的自由函式
 
 
定義於標頭檔案 <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] 非成員函式

比較兩個 std::stop_token 物件
(function) [編輯]
特化 std::swap 演算法
(function) [編輯]

[edit] 備註

stop_token 物件通常不是獨立構造的,而是從 std::jthreadstd::stop_source 檢索的。這使得它與 std::jthreadstd::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