![](/img/trans.png)
[英]When do we need std::shared_future instead of std::future for inter-thread synchronization?
[英]std::shared_future operator= thread safety/ atomic?
一般问题: std :: shared_future :: operator =原子吗?
例如
struct object {
object() {
sf = std::async(std::launch::async, &async_func).share();
}
void change(){
sf = std::async(std::launch::async, &other_async_func).share();
}
void read(){
while (true){ sf.get(); }
}
std::shared_future<int> sf;
};
问题第1部分是否可以调用std::shared_future::operator=
而左侧(例如旧的shared_future
尚未等待/ 异步提供程序仍在运行? 就像在object::change()
。
问题第二部分 ,可以同时调用std::shared_future.get()
其他异步返回对象 /线程来调用std::shared_future::operator=
吗? 像在object::read()
? 编辑:忘了object::read()
,我的意思是当然有他们自己的std::shared_future
但具有相同的共享状态 。
读C ++ 11草案后N3485 §30.6.7:12
shared_future&运算符=(shared_future && rhs)noexcept; 12种效果:
—释放任何共享状态(30.6.4);
— move将rhs的内容分配给* this
问题第1部分仅取决于释放共享状态 ,例如在阅读§30.6.4之后, 销毁共享状态 ,因此我想这意味着第1部分应该为true ,但我不确定。
问题第二部分似乎是错误的 ,因为这是两个步骤,我既不知道移动部分是否是原子的,也不知道如果其他线程位于shared_future::get()
时共享状态被破坏,会发生什么情况。
这些只是[futures.shared_future]中的注释,但它们是相关的:
[注意: shared_future的成员函数不与自己同步 ,但与共享的共享状态同步。 —尾注]
[...]
const R& shared_future::get() const; R& shared_future<R&>::get() const; void shared_future<void>::get() const;
注意:对共享状态下存储的值对象的访问是不同步的 ,因此程序员仅应在
R
上应用那些不会引入数据竞争的操作(1.10)。
因此,只要没有人调用read()
或以其他方式访问sf
则调用change()
很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.