Reputation: 3829
I have two threads running in parallell started from the main thread.
Either thread may fail. If it do so I want to ask the other thread to cancel as well.
In C++ 20 there is std::stop_token
and std::stop_source
.
I have found several examples where the main thread ask all threads to cancel (deferred cancelation).
However I have not found any examples where either worker thread may deferred cancel all other worker threads.
How is this done?
Upvotes: 2
Views: 525
Reputation: 473966
In order for a location of code to be able to request a stop, that location must have a std::stop_source
. In order for a location of code to be able to respond to the stop, it must have a std::stop_token
taken from a particular stop_source
.
Therefore, in order for a location of code to be able to both request and respond to a stop, it must have both the stop_source
and the stop_token
.
Now, since stop_source
s are able to generate stop_token
s, there's no reason why you can't just give the thread function a stop_source
and have it extract a token from it. Of course, this won't be able to use std::jthread
s convenience ability to detect that a thread function whose first argument is a stop_token
and generate a stop_source
, but the nature of your stopping needs wouldn't make that viable anyway.
Also, remember that stop_source
is copyable; the copies all share the same internal stop-state (along with any stop_token
s created from them). So there's no reason to pass them by reference.
Upvotes: 3