2017-04-22 46 views
0

我有一個很難理解爲什麼下面的代碼塊:任務是阻止如果使用未來像

{ 
    std::async(std::launch::async, [] { std::this_thread::sleep_for(5s); 
    // this line will not execute until above task finishes? 
    } 

我懷疑std::async回報std::future臨時這在析構函數的加入任務線程。可能嗎?

的完整代碼如下:

int main() { 
    using namespace std::literals; 

    { 
    auto fut1 = std::async(std::launch::async, [] { std::this_thread::sleep_for(5s); std::cout << "work done 1!\n"; }); 
    // here fut1 in its destructor will force a join on a thread associated with above task. 
    } 
    std::cout << "Work done - implicit join on fut1 associated thread just ended\n\n"; 

    std::cout << "Test 2 start" << std::endl; 
    { 
    std::async(std::launch::async, [] { std::this_thread::sleep_for(5s); std::cout << "work done 2!" << std::endl; }); 
    // no future so it should not join - but - it does join somehow. 
    } 
    std::cout << "This shold show before work done 2!?" << std::endl; 

} 
+1

你是對的,'std :: future'的析構函數一直等到它完成時,如果它是等待共享狀態的最後將來,並且它是由'std :: async'創建的。見[這裏](http://en.cppreference.com/w/cpp/thread/future/~future) – Corristo

+1

@Corristo:請在答案部分**中填寫您的答案。 –

+0

@BoundaryImposition由於我沒有包括解決問題的方法,我不認爲它值得回答。 – Corristo

回答

2

是,std::future通過async返回有等待任務的析構函數要完成的特殊屬性。

這是因爲鬆散的線程是壞消息,而且您必須等待該線程的唯一標記纔是未來的破壞者。

爲了解決這個問題,存儲結果期貨,直到您需要完成結果,或者在極端情況下結束程序。

編寫你自己的線程池系統也是一個好主意;我發現C++線程原語足以編寫線程系統,但在原始程序中使用並不是我在小程序之外鼓勵的東西。