[英]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
.在 C++ 20 中有std::stop_token
和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?这是怎么做到的?
In order for a location of code to be able to request a stop, that location must have a std::stop_source
.为了使代码位置能够请求停止,该位置必须具有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
.为了使代码位置能够响应停止,它必须具有从特定stop_source
获取的std::stop_token
stop_token 。
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
.因此,为了使代码位置能够请求和响应停止,它必须同时具有stop_source
和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.现在,由于stop_source
能够生成stop_token
,所以没有理由不能只给线程 function 一个stop_source
并让它从中提取令牌。 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.当然,这将无法使用std::jthread
的便捷功能来检测第一个参数是stop_token
并生成 stop_source 的线程 function 并生成stop_source
,但是您的停止需求的性质无论如何都不会使其可行。
Also, remember that stop_source
is copyable ;另外,请记住stop_source
是可复制的; the copies all share the same internal stop-state (along with any stop_token
s created from them).这些副本都共享相同的内部停止状态(以及从它们创建的任何stop_token
)。 So there's no reason to pass them by reference.所以没有理由通过引用传递它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.