Andy
Andy

Reputation: 3829

Can I use std::stop_source to deferred cancel all worker threads from a worker thread?

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

Answers (1)

Nicol Bolas
Nicol Bolas

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_sources are able to generate stop_tokens, 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::jthreads 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_tokens created from them). So there's no reason to pass them by reference.

Upvotes: 3

Related Questions