为什么没有未来::等待()块
问题描述:
#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()
阻止?
答
问题不在于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不建议拆卸螺纹。 –
答
或者您可以分离线程,并使用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;
}
我建议你看一看的std ::异步 – LeDYoM