stop_source and stop_token - DryPerspective/Cpp17_jthread GitHub Wiki

Stop Source and Stop Token

stop_source and stop_token manage stop state potentially associated with several constructs. The stop_source provides the means to request a stop, and when a stop is requested; all associated stop_tokens are able to see the request, all registered stop_callback callbacks are executed, and any condition_variable_any waiting with the associated stop_token will be awoken. Once a stop request has been issued it cannot be rescinded, and further stop requests have no effect. Tag type dp::nostopstate_t and its associated constant dp::nostopstate may be used to construct a stop_source with no associated stop state, for cases such as deferred initialization.

A stop_token provides a read-only, owning view of the underlying stop state. It can query whether a stop is possible or has been requested, but cannot issue stop requests of its own. The intended use is that users of the stop source have their own token which they can use to query the state; but are protected from unintentionally issuing a stop request. Stop tokens are safe to pass by value, and can be used alongside stop_callback objects to register a callback with the stop source, and used with condition_variable_any to be notified when a stop is requested.

Both the stop_source and stop_token provided in this repo are declared in stop_token.h and exist in namespace dp.

Interface

dp::stop_source Interface

request_stop Atomically issues a stop request to all associated stop_source and stop_token objects; and executes all registered callbacks in the context of the thread which requested the stop.
swap Swaps the managed state of two stop_source objects. Does not throw.Both a member and free function are provided.
get_token Returns a stop_token associated with the source's stop state.
stop_requested Returns whether a stop request has been issued.
stop_possible Returns whether it would be possible to request a stop, ie whether the source has any associated stop state.
operator==operator!= Compares whether two stop_source objects are associated with the same stop state.NB: std::stop_source doesn't need an explicit operator!= due to the equality and comparison operator changes in C++20. We include one here for completeness of functionality.

dp::stop_token Interface

swap Swaps the managed state of two stop_token objects. Does not throw.Both a member and free function are provided.
stop_requested Returns whether a stop request has been issued.
stop_possible Returns whether it would be possible to request a stop, ie whether the token's source has any associated stop state.
operator==operator!= Compares whether two stop_token objects are associated with the same stop state.NB: std::stop_token doesn't need an explicit operator!= due to the equality and comparison operator changes in C++20. We include one here for completeness of functionality.