2016-10-13 71 views
1

我對C++ 11功能std::async頗爲陌生,我無法理解爲什麼下面的代碼從不打印bar在構造函數中使用std :: async

難道有人能爲我揭開一些啓示嗎?此頁面上

class Thready { 

    public: 

    Thready() { 
     std::async(std::launch::async, &Thready::foo, this); 
    } 

    void foo() { 
     while (true) { 
      std::cout << "foo" << std::endl; 
     } 
    } 

    void bar() { 
     while (true) { 
      std::cout << "bar" << std::endl; 
     } 
    } 
}; 

int main() { 
    Thready t; 
    t.bar(); 
} 

回答

2

參閱「說明」部分:http://en.cppreference.com/w/cpp/thread/async

實現方式可以通過使在附加(實現定義的)位延伸 的std ::異步的第一過載的行爲 默認啓動策略。實施定義的啓動 策略的示例是同步策略(立即執行,在異步 調用中執行)和任務策略(類似於異步,但線程本地並不清除 )如果從std :: future獲得std :: future, :異步不從 移動或結合到參考,在std ::未來的析構函數將在充分表達的端部阻塞 直到異步操作 完成,基本上使代碼如以下同步:

std::async(std::launch::async, []{ f(); }); // temporary's dtor waits for f() 
std::async(std::launch::async, []{ g(); }); // does not start until f() completes 

(注意destr比調用其他方式取得的std :: uctors期貨 到std ::異步從未塊)

TL; DR:

嘗試的std ::異步調用的返回值保存到一些變量:

auto handle = std::async(std::launch::async, &Thready::foo, this); 

編輯:

像您期望下面的代碼應該工作。

#include <future> 
#include <iostream> 

class Thready { 

    public: 

    Thready() { 
     handle = std::async(std::launch::async, &Thready::foo, this); 
    } 

    void foo() { 
     while (true) { 
      std::cout << "foo" << std::endl; 
     } 
    } 

    void bar() { 
     while (true) { 
      std::cout << "bar" << std::endl; 
     } 
    } 

    std::future<void> handle; 
}; 

int main() { 
    Thready t; 
    t.bar(); 
} 
+0

很好,很有道理。是否有可能使foo無效? – user695652

+0

是的,請參閱編輯。顯然這裏有一個模板專門化,'std :: future '。它甚至有'void get()'方法!我從來沒有用過它。 –