std::stop_source
來自 cppreference.com
定義於標頭檔案 <stop_token> |
||
class stop_source; |
(C++20 起) | |
stop_source
類提供了發出停止請求的手段,例如用於 std::jthread 取消。為一個 stop_source
物件發出的停止請求對所有具有相同關聯停止狀態的 stop_source
和 std::stop_token 可見;為關聯的 std::stop_token 註冊的任何 std::stop_callback 將被呼叫,並且任何等待關聯的 std::stop_token 的 std::condition_variable_any 物件將被喚醒。
一旦請求停止,就不能撤回。額外的停止請求將沒有效果。
目錄 |
[編輯] 成員函式
構造新的 stop_source 物件(public member function) | |
銷燬 stop_source 物件(public member function) | |
賦值 stop_source 物件(public member function) | |
修改器 | |
對關聯的停止狀態(如果有)發出停止請求 (public member function) | |
交換兩個 stop_source 物件(public member function) | |
觀察器 | |
返回關聯停止狀態的 stop_token (public member function) | |
檢查是否已請求關聯的停止狀態停止 (public member function) | |
檢查關聯的停止狀態是否可以請求停止 (public member function) |
[編輯] 非成員函式
(C++20) |
比較兩個 std::stop_source 物件(function) |
(C++20) |
特化 std::swap 演算法 (function) |
[編輯] 輔助標記
(C++20) |
一個標記,用於 stop_source 在構造時指示沒有關聯的停止狀態(tag) |
[編輯] 注意
為了 std::jthread 取消的目的,應該從 std::jthread 物件使用 get_stop_source() 來檢索 stop_source
物件;或者直接從 std::jthread 物件使用 request_stop() 來請求停止。這將使用與傳遞給 std::jthread 的被呼叫函式引數(即在其執行緒上執行的函式)相同的關聯停止狀態。
然而,對於其他用途,可以使用預設建構函式單獨構造 stop_source
,這將建立新的停止狀態。
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_jthread |
201911L |
(C++20) | 停止標記和連線執行緒 |
[編輯] 示例
執行此程式碼
#include <chrono> #include <iostream> #include <stop_token> #include <thread> using namespace std::chrono_literals; void worker_fun(int id, std::stop_token stoken) { for (int i = 10; i; --i) { std::this_thread::sleep_for(300ms); if (stoken.stop_requested()) { std::printf(" worker%d is requested to stop\n", id); return; } std::printf(" worker%d goes back to sleep\n", id); } } int main() { std::jthread threads[4]; std::cout << std::boolalpha; auto print = [](const std::stop_source& source) { std::printf("stop_source stop_possible = %s, stop_requested = %s\n", source.stop_possible() ? "true" : "false", source.stop_requested() ? "true" : "false"); }; // Common source std::stop_source stop_source; print(stop_source); // Create worker threads for (int i = 0; i < 4; ++i) threads[i] = std::jthread(worker_fun, i + 1, stop_source.get_token()); std::this_thread::sleep_for(500ms); std::puts("Request stop"); stop_source.request_stop(); print(stop_source); // Note: destructor of jthreads will call join so no need for explicit calls }
可能的輸出
stop_source stop_possible = true, stop_requested = false worker2 goes back to sleep worker3 goes back to sleep worker1 goes back to sleep worker4 goes back to sleep Request stop stop_source stop_possible = true, stop_requested = true worker3 is requested to stop worker1 is requested to stop worker2 is requested to stop worker4 is requested to stop