2017-02-09 39 views
1

C++ 11C++的std ::異步不會產生一個新的線程

int main(int argc, char** argv) { 
    std::async(std::launch::async, [](){ 
     while(true) cout << "async thread" <<endl; 
    }); 
    while(true) cout << "main thread" << endl; 
    return 0; 
} 

我預期的輸出應與async threadmain thread被交錯的東西,因爲應該有2個不同的線程。

但事實並非如此。

它輸出:

async thread 
async thread 
async thread 
async thread 
... 

我想,只有一個線程。有人可以告訴我爲什麼它不會產生一個新線程std::async?謝謝。

+3

http://en.cppreference.com/w/cpp/thread/async - 閱讀註釋。 – chris

回答

5

更改爲這樣:

auto _ = std::async(std::launch::async, [](){ 
    while(true) cout << "async thread" <<endl; 
}); 

文獻:

如果從標準::異步獲得的std ::未來不是從移動或結合 與參考比較,的析構函數std :: future將在完整表達式的末尾 處阻止,直到異步操作完成, 本質上使得代碼如下同步:

std :: async(std :: launch :: async,[] {f(); }); //臨時的dtor爲f()std :: async(std :: launch :: async,[] {g();})等待 ; //不啓動 直到f()完成