2015-09-01 71 views
1

一般問題:是std :: shared_future :: operator = 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()一樣。

問題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 &運算符=(shared_future & &右)noexcept; 12影響:

- 釋放任何共享狀態(30.6.4);

- 移動分配RHS爲*此

問題第1部分僅取決於釋放共享狀態例如內容在閱讀§30.6.4,後摧毀共享狀態所以我想這意味着,第1部分應該是真的,但我不確定。

問題第2部分似乎是假,因爲這2個步驟,我沒有不知道此舉部分是原子也不是,如果發生什麼事,如果共享狀態被破壞,而其他線程都在shared_future::get()

回答

1

這些都是隻有在[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)的操作。

所以調用change()是罰款,只要沒有人打電話read()或訪問sf