是否有可能不等待来自线程函数的返回值?例如稍后检查值是否曾经返回,并在该函数执行时执行其他操作?我的意思是,如果你不得不等待函数返回,那么它就不是真正的多线程,因为你可以直接调用函数。C++稍后从线程函数中获取返回值
#include <thread>
#include <future>
int func_1(int x)
{
return x; //Assume this takes several seconds to complete
}
int main()
{
auto future = std::async(func_1, 2);
int number = future.get(); //Whole program waits for this
//More code later
while(!number) //Check if number ever returned?
{
//Wait for it or assume some error/default
}
return 0;
}
*“整个程序等待这个”*当然是的,你明确地告诉过它。在需要之前不要“得到”结果。阅读[文档](http://en.cppreference.com/w/cpp/thread/future)。 –
您可以明确使用启动类型'std :: async(std :: launch :: async,...)',否则不能确保函数在单独的线程中运行。 – Trevir