wiki:hpp-stop-token
Table of Contents
<stop_token>
<stop_token> provides std::stop_token and std::stop_source for cooperative cancellation (C++20). A stop_token can be checked to see if cancellation was requested, and callbacks can be registered to run when cancellation occurs.
Use it to enable graceful shutdown of background tasks without forceful thread termination.
Example
This example uses jthread to run a worker with a stop_token that can be checked for cancellation requests.
// compile: g++ -std=c++20 -pthread -o stoptokenexample stoptokenexample.cpp // run: ./stoptokenexample // description: cooperative cancellation with stop_token #include <stop_token> #include <thread> #include <iostream> void worker(std::stop_token st) { for (int i = 0; i < 10; ++i) { if (st.stop_requested()) { std::cout << "stopping\n"; break; } std::cout << "working... " << i << "\n"; std::this_thread::sleep_for(std::chrono::milliseconds(50)); } } int main() { std::jthread t(worker); std::this_thread::sleep_for(std::chrono::milliseconds(150)); t.request_stop(); return 0; }
wiki/hpp-stop-token.md · Last modified: by 127.0.0.1
