2013-11-26 38 views
3

我對C++期貨/承諾的行爲有些困惑。C++ 11期貨/承諾中沒有狀態錯誤

的代碼如下

std::future<std::string> method() { 
     std::promise<std::string> pr; 
     std::future<std::string> ft = pr.get_future(); 

     std::thread t(     
      [](std::promise<std::string> p) 
      {      
       p.set_value("z"); 
      },      
      std::move(pr)   
     );      
     t.detach();      

     return std::move(ft);   
} 

當我運行的代碼,有一個例外__throw_future_error((int)future_errc::no_state);std::future<std::string> ft = pr.get_future();

拋出的任何想法,爲什麼會出現這種情況?

編輯:

所以,我有一個展示該問題的小例子。 Coliru(帶有g ++ 4.8和更新的stdlib)好像運行的很好,但是當涉及到我的工作站時,它失敗了。

http://coliru.stacked-crooked.com/a/711e182594cbe7d3

我與

# gcc 4.7.3 
g++ -g -std=c++11 -lpthread t.cpp -o t 

編譯
# clang 3.2.1 
clang++ -g -std=c++11 -lpthread t.cpp -o t 

的libstdC++版本是3.4.17

工作站是Linux Mint的15

+2

你正在使用哪種編譯器?在gcc/clang的情況下,你是否使用-pthread編譯?代碼看起來很好,它適用於我(gcc-4.8,gcc-4.9快照,一些svn叮噹3.3)。 – inf

+0

Clang,用-lpthread -std = C++編譯11。線程實際上在程序中運行,因爲我有兩個其他線程在運行。 –

+0

[在coliru編譯時沒有問題](http://coliru.stacked-crooked.com/a/aa2096535a92116d)。 – Casey

回答

1

這看起來像一個錯誤。指定promise的默認構造函數爲promise構造共享狀態。從pr.get_future()返回的future應該指向那個共享狀態。

-stdlib=libc++您的選擇嗎?

+0

不幸的是沒有。 -stdlib = libC++給出文件未找到。我想我必須檢查我的stdlib版本並返回一些版本號。 –

+0

它看起來像一個錯誤。我已經更新了gcc(4.8),stdlib和clang(3.3),它的工作原理。謝謝 :) –