简体   繁体   English

std::coroutine_handle 线程是否安全?

[英]Is std::coroutine_handle thread safe in any way?

Are there any parts of std::coroutine_handle that are defined as thread safe in the standard?标准中是否有std::coroutine_handle被定义为线程安全的部分?

I could for example see std::coroutine_handle::done() being implemented with an atomic variable, which would allow for completion checks without locking everything first.例如,我可以看到std::coroutine_handle::done()使用原子变量实现,这将允许完成检查而无需先锁定所有内容。

But if nothing related to thread safety is defined in the standard then I would have to assume the worst case scenario and always lock everything.但是如果标准中没有定义与线程安全相关的任何内容,那么我将不得不假设最坏的情况并始终锁定所有内容。

None of the functions of coroutine_handle are specified to not provoke data races. coroutine_handle的所有功能都没有被指定为不引发数据竞争。 Therefore, the standard library's common rules apply: concurrently calling any functions with an object provokes a data race on that object unless all potentially conflicting functions access the object via a const pointer/reference (like const members).因此,标准库的通用规则适用:同时调用具有对象的任何函数会引发对该对象的数据竞争,除非所有潜在冲突的函数都通过const指针/引用(如const成员)访问该对象。

The observers, such as explicit operator bool() and done are both const and thus do not provoke a data race, unless other, non- const functions are being called.观察者,例如explicit operator bool()done都是const ,因此不会引发数据竞争,除非正在调用其他非const函数。 And of course, operator() and resume() are both non- const , and thus can provoke data races with the observers.当然, operator()resume()都是非const ,因此会引发与观察者的数据竞争。 However, the observers have the precondition that the handle in question is suspended, so you couldn't really do that anyway.然而,观察者的前提是有问题的句柄被挂起,所以无论如何你都不能真正做到这一点。

Really though, you shouldn't be trying to access a handle concurrently to begin with.但实际上,您不应该一开始就尝试同时访问句柄。 The promise type should manage the handle for these scenarios, and any interaction between the future and the handle should happen through the promise.承诺类型应该管理这些场景的句柄,未来和句柄之间的任何交互都应该通过承诺发生。 And if concurrent interaction is needed, the promise can provide it.如果需要并发交互,promise 可以提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM