2016-12-16 7 views
6
#include <iostream> 
#include <string> 
#include <thread> 
#include <future> 


int main() 
{ 
    auto pms = std::promise<std::string>(); 
    auto ftr = pms.get_future(); 

    std::thread([&](){pms.set_value("hello world");});  
    ftr.wait(); 
    std::cout << ftr.get() << std::endl; 

    return 0; 
} 

this linkによると、結果は使用可能になるまでブロックされます。
future :: wait()ブロックがなぜ発生しないのですか?

ただし、上記のコードでは何も印刷できません。明らかに、メインスレッドはpms.set_valueのスレッドが終了する前に終了しています。

なぜ、ftr.wait()ブロックされますか?

+0

私はスレッドを取り外す示唆ないためにはstd ::を見 – LeDYoM

答えて

9

問題は、std::future::waitはブロックされません。実際の問題は、あなたが作成したスレッドと、そのスレッドの実行と、メインスレッドのstd::thread(一時的な)オブジェクトの破壊との間で競合状態が発生していることです。

スレッドがまだ結合可能であれば、abortがデストラクタでstd::threadという名前で呼び出されます。

の作業コード:

#include <iostream> 
#include <string> 
#include <thread> 
#include <future> 
#include <chrono> 

int main() 
{ 
    auto pms = std::promise<std::string>(); 
    auto ftr = pms.get_future(); 

    std::thread thread ([&](){pms.set_value("hello world");});  
    ftr.wait(); 
    std::cout << ftr.get() << std::endl; 
    thread.join(); 
    return 0; 
} 

注意、あなたが明示的threadに参加していない場合、それはmainが速く、その作業を行うことができている可能性がありますから、あなたはまだthread缶よりも、(同じ競合状態を持っているでしょう自分自身をクリーンアップ実施例の

デモ:。。here

+3

Upvoted非同期を取るためにあなたをお勧めします。 –

0

また、あなたがスレッドを切り離し、むしろよりもpromise::set_value_at_thread_exitを使用することができます

#include <iostream> 
#include <string> 
#include <thread> 
#include <future> 
#include <chrono> 


int main() 
{ 
    auto pms = std::promise<std::string>(); 
    auto ftr = pms.get_future(); 

    std::thread([&](){pms.set_value_at_thread_exit("hello world");}).detach();  
    ftr.wait(); 
    std::cout << ftr.get() << std::endl; 

    return 0; 
} 
関連する問題