std :: shared_future运算符=线程安全性/原子性? [英] 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()
中一样.
Question Part 1 Is it OK to call std::shared_future::operator=
while the left, e.g. old shared_future
, has not been waited on/asynchronous provider still running? Like in object::change()
.
问题第2部分,可以同时调用其他异步返回对象/线程中的 std :: shared_future :: operator =
调用 std :: shared_future.get()
?就像在 object :: read()
中一样?忘记 object :: read()
,我的意思是当然使用他们自己的 std :: shared_future
,但具有相同的共享状态.
Question Part 2 Is it OK to call std::shared_future::operator=
while other asynchronous return objects / threads that are concurrent calling std::shared_future.get()
? Like in object::read()
?
Forget object::read()
, I mean of course with their own std::shared_future
but the same shared state.
在阅读C ++ 11草案后 N3485 §30.6.7:12
After reading of C++11 draft N3485 §30.6.7:12
shared_future&运算符=(shared_future&& rhs)noexcept;12种效果:
shared_future& operator=(shared_future&& rhs) noexcept; 12 Effects:
-释放任何共享状态(30.6.4);
— releases any shared state (30.6.4);
— move将rhs的内容分配给* this
— move assigns the contents of rhs to *this
问题第1部分仅取决于释放共享状态,例如在阅读了§30.6.4之后,破坏了共享状态,所以我想这意味着第1部分应该是正确的,但是我不确定.
Question Part 1 depends solely on releasing a shared state, e.g. after reading of §30.6.4, destroying a shared state, so I guess that means Part 1 should be true, but I'm not sure.
问题部分2似乎是错误的,因为这是两个步骤,我既不知道移动部分是否是原子部分,也不知道如果共享状态被破坏会发生什么情况而其他线程在 shared_future :: get()
中.
Question Part 2 seems to be false, because these are two steps and I neither know if the move part is atomic nor if what happens if the shared state is destroyed while other threads are in shared_future::get()
.
推荐答案
这些只是[futures.shared_future]中的注释,但它们是相关的:
These are only notes in [futures.shared_future], but they're relevant:
[注意: shared_future的成员函数不与其自身同步,但它们与共享的共享状态.-尾注]
[ Note: Member functions of shared_future do not synchronize with themselves, but they synchronize with the shared shared state. —end note ]
[...]
const R& shared_future::get() const;
R& shared_future<R&>::get() const;
void shared_future<void>::get() const;
注意:对存储在共享状态中的值对象的访问是不同步的,因此程序员应该仅在 R
上应用那些不会引起数据争用的操作(1.10).
Note: access to a value object stored in the shared state is unsynchronized, so programmers should
apply only those operations on R
that do not introduce a data race (1.10).
因此,只要没有人调用 read()
或以其他方式访问 sf
,则调用 change()
很好.
So calling change()
is fine as long as nobody is calling read()
or otherwise accessing sf
.
这篇关于std :: shared_future运算符=线程安全性/原子性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!