std::shared_future operator= 线程安全/原子操作吗?

3

一般问题: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 在左侧,例如旧的shared_future没有等待/异步提供者仍在运行时,是否可以调用std::shared_future::operator=?就像在object::change()中一样。

问题2 在其他并发调用std::shared_future.get()异步返回对象/线程上调用std::shared_future::operator=是否可以?就像在object::read()中一样? 编辑:忘记了object::read(),我当然是指他们自己的std::shared_future但是相同的共享状态

阅读C++11草案后N3485 §30.6.7:12

shared_future& operator=(shared_future&& rhs) noexcept; 12 Effects:

— releases any shared state (30.6.4);

— move assigns the contents of rhs to *this

问题1仅取决于释放共享状态,例如在阅读§30.6.4之后,销毁共享状态,因此我认为这意味着部分1应该是正确的,但我不确定。

问题2似乎是错误的,因为这些是两个步骤,我既不知道移动部分是否原子化,也不知道当其他线程处于shared_future::get()时如果共享状态被销毁会发生什么。

1个回答

2

这只是[futures.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;

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()就没问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接