BDE 4.14.0 Production release
|
Provide an allocator-aware standard-compliant stop_source type.
Canonical header: bsl_stop_token.h
This component defines the bsl::stop_callback
, bsl::stop_source
, and bsl::stop_token
classes, which provide a thread-safe facility for requesting a cancellation (known as "making a stop
request" in the standard), observing cancellation requests, and registering callbacks to be invoked when a cancellation is requested. The interfaces of these classes are identical to those of their std
counterparts (available in C++20 and later), except that bsl::stop_callback
is allocator-aware and bsl::stop_source
has a constructor that accepts an allocator, which is used to allocate the stop state.
This section illustrates intended use of this component.
bsl::stop_token
can be used to implement a condition variable wrapper that allows a wait to be interrupted by a stop. (In C++20, such functionality is available as std::condition_variable_any
.) The wrapper must hold a bsl::stop_token
object that is used to check whether a stop has been requested, before entering a wait. It is also necessary to ensure that the thread that requests a stop is able to actually wake up any threads that are waiting; for this reason, a bsl::stop_callback
must be used to notify the waiting threads automatically when a stop is requested. For simplicity, we will only implement one signature for the wait
method.
The bsl::stop_token
object passed to InterruptibleCV::wait
will reflect that a stop has been requested only after request_stop is called on a bsl::stop_source
object from which the bsl::stop_token
was derived (or a copy of that bsl::stop_source
).
In the UsageExample
class below, the child thread will wait until the value of d_counter
is at least 50. However, because the main thread requests a stop after setting d_counter
to 10, the child thread wakes up.
Due to the levelization of this component, the example above uses the C++11 standard library instead of bslmt::Mutex
and similar components, and will therefore compile only in C++11 and higher. However, a similar example can be implemented in C++03 by using bslmt
components in a package that is levelized above bslmt
.