2012-03-16 62 views
17

我對std::async功能的行爲與std::launch::async政策從異步返回& std::future對象的一些問題。性病的行爲::異步用的std ::推出::異步政策

在以下代碼中,主線程等待完成foo()async創建的線程的調用。

#include <thread> 
#include <future> 
#include <iostream> 

void foo() 
{ 
    std::cout << "foo:begin" << std::endl; 
    std::this_thread::sleep_for(std::chrono::seconds(10)); 
    std::cout << "foo:done" << std::endl; 
} 

int main() 
{ 
    std::cout << "main:begin" << std::endl; 
    { 
    auto f = std::async(std::launch::async, foo); 
    // dtor f::~f blocks until completion of foo()... why?? 
    } 
    std::this_thread::sleep_for(std::chrono::seconds(2)); 
    std::cout << "main:done" << std::endl; 
} 

而且我知道http://www.stdthread.co.uk/doc/headers/future/async.html

與返回性病的 異步狀態相關聯的最後一個未來對象的析構函數::未來應阻止,直到 未來做好準備。

我的問題是:

  • Q1。這種行爲是否符合當前的C++標準?第二季度銷售價格爲
  • 。如果Q1的答案是肯定的,哪些陳述說?
+0

這個標準的驚人之處在於,經常一個腳註完全改變了一個章節...... – orlp 2012-03-16 07:39:07

回答

16

是的,這是C++標準所要求的。 30.6.8 [futures.async]段5,最終子彈:

- 相關線程完成與(1.10)的從成功地檢測到共享狀態或與返回就緒狀態的第一函數的返回同步從最後一個釋放共享狀態的函數中,以先發生者爲準。

唯一的std:future的析構函數滿足該條件,因此必須等待線程的完成。

+1

OP的代碼在VS2012中不起作用。它不會阻止'將來'析構函數。這是一種錯誤,還是微軟只是接受了Sutter的建議,不要阻止dtors? – 2013-02-24 10:30:03

+0

微軟選擇實施Herb Sutter的建議,不要在析構函數中阻止。 – 2013-02-24 17:48:43

+0

這種行爲是一個大問題,但我擔心現在修復標準爲時已晚。微軟選擇實施非標準行爲是因爲他們不同意這一點,這隻會讓跨平臺開發人員感到困難。 – cdmh 2013-04-15 16:29:54