skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
hpp-stop-token
This page is read only. You can view the source, but not change it.
# <stop_token> **[<stop_token>](https://en.cppreference.com/w/cpp/header/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. This example uses jthread to run a worker with a stop_token that can be checked for cancellation requests. ```cpp // 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; } ```
Page Tools
Show pagesource
Backlinks
Back to top