C++ 稍后从线程函数中获取 return 值
C++ Get the return value from a threaded function later
是否可以不等待线程函数的 return 值?例如稍后检查该值是否 returned 并在该函数执行时做其他事情?我的意思是,如果您必须等待函数执行 return,那么它并不是真正的多线程,因为您可以直接调用该函数。
#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;
}
您可以通过零超时调用 future::wait_for
检查未来是否准备就绪,并检查返回值是否等于 future_status::ready
。
顺便说一句:std::async
returns 特殊期货,如果你真的想使用它,你应该考虑一下。更详细的信息:http://scottmeyers.blogspot.com/2013/03/stdfutures-from-stdasync-arent-special.html
您正在立即请求结果,而不是做其他事情然后在需要时获得结果。如果你这样做:
int main()
{
auto future = std::async(func_1, 2);
//More code later
int number = future.get(); //Whole program waits for this
// Do something with number
return 0;
}
然后您可以在 More code later
位中做其他事情,然后在需要结果时通过调用 get()
.
进行阻塞
或者,您可以使用 wait_for or wait_until 进行轮询以查看该值是否可用,如果结果尚未准备好,则执行一些操作。
是否可以不等待线程函数的 return 值?例如稍后检查该值是否 returned 并在该函数执行时做其他事情?我的意思是,如果您必须等待函数执行 return,那么它并不是真正的多线程,因为您可以直接调用该函数。
#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;
}
您可以通过零超时调用 future::wait_for
检查未来是否准备就绪,并检查返回值是否等于 future_status::ready
。
顺便说一句:std::async
returns 特殊期货,如果你真的想使用它,你应该考虑一下。更详细的信息:http://scottmeyers.blogspot.com/2013/03/stdfutures-from-stdasync-arent-special.html
您正在立即请求结果,而不是做其他事情然后在需要时获得结果。如果你这样做:
int main()
{
auto future = std::async(func_1, 2);
//More code later
int number = future.get(); //Whole program waits for this
// Do something with number
return 0;
}
然后您可以在 More code later
位中做其他事情,然后在需要结果时通过调用 get()
.
或者,您可以使用 wait_for or wait_until 进行轮询以查看该值是否可用,如果结果尚未准备好,则执行一些操作。