为什么 future::wait() 块

Why doesn't future::wait() block

本文关键字:wait future 为什么      更新时间:2023-10-16
#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;
}

根据此链接, std::future::wait块直到结果可避免。

但是,上面的代码无法打印任何内容。显然,主线程在pms.set_value的线程完成之前已经完成。

为什么不 ftr.wait()块?

问题不是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更快地完成工作。

工作的演示示例:此处。

或者您可以分离线程并使用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;
}