std::stop_token::stop_possible
來自 cppreference.com
< cpp | thread | 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() 獲得了 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