2016-12-16 81 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,std::future::wait阻塞,直到结果变得可用。
为什么没有未来::等待()块

但是,上面的代码不能打印任何东西。显然主线程在完成pms.set_value的线程之前已经完成。

为什么ftr.wait()阻止?

+0

我建议你看一看的std ::异步 – LeDYoM

回答

9

问题不在于std::future::wait不阻止。真正的问题是,你在产生的线程,做它的工作以及破坏主线程中的std::thread(临时)对象之间存在竞争条件。

因此,如果线程仍可连接,则在std::thread的析构函数中调用abort

工作代码:

#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而不是set_value

#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; 
}