1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
Before using hi(stop_callback)tt(std::stop_callback) objects the
tthi(stop_token) header file must be included.
In addition to merely ending thread functions via tt(jthread's request_stop)
member function it's also possible to associate hi(callback) em(callback
functions) with tt(request_stop), which are executed when tt(request_stop) is
called. In situations where callback functions are registered when the
thread function has already been stopped the callback functions are
immediately called when they are being registered (registering callback
functions is covered below).
Note that multiple callback functions can be registered. However, the order in
which these callback functions are run once the thread is stopped is not
defined. Moreover, exceptions may not leave callback functions or the program
ends by calling tt(std::terminate).
Callback functions are registered by objects of the class
tt(std::stop_callback). The class tt(stop_callback) offers the following
constructors:
itemization(
itt(explicit stop_callback(std::stop_token const &st,
Function &&cb) noexcept;)
itt(explicit stop_callback(std::stop_token &&st, Function &&cb) noexcept;)
)
Notes:
itemization(
itt(Function) can be the name of a (void) function without parameters or
it can be an (anonymous or existing) object offering a parameter-less
(void) function call operator. The functions do not necessarily have
to be void functions, but their return values are ignored;
it() The tt(noexcept) is only used if tt(Function) is also declared as
tt(noexcept) (if tt(Function) is the name of a functor-class then
tt(noexcept) is used if its constructor is declared with
tt(noexcept));
it() The class tt(stop_callback) does not offer copy/move construction and
assignment.
)
Here is the example used in the previous section, this time defining a
callback function. When running this program its output is
verb( next
next
next
stopFun called via stop_callback)
verbinsert(-ns4 //stop examples/stopcallback.cc)
The function tt(fun) is identical to the one shown in the previous
section, but tt(main) defines (line 19) the tt(stop_callback) object tt(sc),
passing it tt(thr's get_stop_token's) return value and the address of the
function tt(stopFun), defined in lines 10 thru 13. In this case once
tt(request_stop) is called (line 23) the callback function tt(stopFun) is
called as well.
|