2015-10-16 83 views
0

我想要一個任務,如果它正在運行的時間可以是killable。std :: async中的奇怪行爲

,所以我tryng這樣的:

#include <iostream> 
#include <future> 

using namespace std; 

int main() 
{ 
    auto handle = std::async(std::launch::deferred,[] 
         { 
          cout<<"Initializing thread..."<<endl; 
          this_thread::sleep_for(std::chrono::seconds(5)); 
         } 
       ); 

    cout<<"Starting..."<<endl; 
    handle.wait_for(std::chrono::seconds(2)); 

    cout<<"Finished correctly"<<endl; 
    return 0; 
} 

的輸出繼電器:

開始......

正確結束

爲什麼不打印「初始化線程......「?我嘗試調換兩個chronos並且無論如何都不工作

回答

1

您從不要求任務的結果,因此它不會被調度。

用代替deferred,你會得到你所期望的。

+0

問題是,如果我創建一個線程,我將無法殺死它 – amchacon

+0

重要的是,你不能用'std :: async'創建一個線程。你不控制。 – sehe

+0

好的,我檢查了這個:http://en.cppreference.com/w/cpp/thread/future_status – amchacon

1

deferred只計算在定時限wait功能。如果您更改爲:

handle.wait(); 

您將看到該線程在該位置開始。

+0

這不是OP想要做的。否則,你可以調用.get() – sehe