From cppreference.com
classstop_token;(since C++20)The stop_token class provides the means to check if a stop request has been made or can be made, for its associated
object. It is essentially a thread-safe "view" of the associated stop-state.
The stop_token can also be passed to the constructor of
, such that the callback will be invoked if the stop_token's associated
is requested to stop. And stop_token can be passed to the interruptible waiting functions of
, to interrupt the condition variable's wait if stop is requested.
Member alias templates
Type Definition callback_type<Callback>(since C++26)std::stop_callback<Callback>Member functions
constructs new stop_token object
(public member function)
destructs the stop_token object
(public member function)
assigns the stop_token object
(public member function)
Modifiers
swaps two stop_token objects
(public member function)
Observers
checks whether the associated stop-state has been requested to stop
(public member function)
checks whether associated stop-state can be requested to stop
(public member function)
Non-member functions
Notes
A stop_token object is not generally constructed independently, but rather retrieved from a
or
. This makes it share the same associated stop-state as the
or
.
macroValueStdFeature
(C++20)
and
Example
Run this code
#include<iostream>#include<thread>usingnamespacestd::literals::chrono_literals;voidf(std::stop_tokenstop_token,intvalue){while(!stop_token.stop_requested()){std::cout<<value++<<' '<<std::flush;std::this_thread::sleep_for(200ms);}std::cout<<std::endl;}intmain(){std::jthreadthread(f,5);// prints 5 6 7 8... for approximately 3 secondsstd::this_thread::sleep_for(3s);// The destructor of jthread calls request_stop() and join().}Possible output:
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19