c++ - std::shared_future operator=线程安全/原子?

标签 c++ multithreading c++11 std future

一般问题: 是 std::shared_future::operator= atomic 吗?

例如

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() 中一样。

问题第 2 部分 是否可以调用 std::shared_future::operator= 而其他异步返回对象/并发线程调用 std::shared_future.get()?就像在 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() 中。

最佳答案

这些只是 [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() 就没问题。

关于c++ - std::shared_future operator=线程安全/原子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32333219/

相关文章:

c++ - 封装boost thread_group。关于ids和同步的问题

c++ - 为什么模板函数中的 std::is_array 不区分 int 和 array 类型?

c++ - 类方法作为函数参数

c++ - Sun Studio 和 "",第 1 行 : Illegal flag (-)

c++ - 在 Release 模式下访问时 vector 大小为 0

c++ - I/O 约束性能 - 加速?

c++ - MongoDB 示例无法使用不同的标志进行编译

c++ - 使用自定义扩展名保存文件

c++ - 为什么编译器不会拒绝以加法运算符开头的行?

c++ - 对于 boost io_service,是否只有一个线程在 epoll_wait 上阻塞?