std::async()、std::future创建后台任务并返回值。希望线程返回一个结果。
std::async()是个函数模板,用来启动一个异步任务,启动这个异步任务之后,它返回一个std::future对象,这个std::future包含线程入口函数返回的结果(线程返回的结果),我们可以调用future的成员函数get()来获取。
int test(int x)
{
cout << "Child threadID:" << std::this_thread::get_id() << endl;
cout << "x:" <<x<< endl;
this_thread::sleep_for(std::chrono::seconds(5));
return x + 100;
}
void main()
{
cout << "main threadID:" << std::this_thread::get_id() << endl;
//创建一个线程,并开始运行,并不会卡在这里。
std::future<int> fut = std::async(test, 11);
Sleep(1000);
for (int i = 0; i < 5;i++)
{
cout << "我在处理耗时任务" << i << endl;
Sleep(1000);
}
int nRes = fut.get();
cout << "nRes:" << nRes << endl;
system("pause");
}
结果:
注意:如果std::async(…),开启的线程,如果调用get(),线程内部没有执行完,会阻塞在get()所在的地方;如果不使用get(),主线程退出的时候也会等待该子线程执行完毕才会退出,如果对于 int main() {…,return 0;},会卡在return 0;语句。
当然也可以使用类的成员函数,代码如下:
class A
{
public:
int test(int x)
{
cout << "Child threadID:" << std::this_thread::get_id() << endl;
cout << "x:" << x << endl;
this_thread::sleep_for(std::chrono::seconds(5));
return x + 100;
}
};
void main()
{
A a;
cout << "main threadID:" << std::this_thread::get_id() << endl;
std::future<int> fut = async(&A::test,&a, 11);
int nRes = fut.get();
cout << "nRes:" << nRes << endl;
system("pause");
}
结果:
从结果的线程id可以看出,并没有创建新的线程,子线程ID
和主线程是一样的。这个问题很奇怪,我也不知道原因,如果有谁知道,请告我一声。
那如何让其开启一个线程呢?使用launch::async
部分代码如下:
void main()
{
A a;
cout << "main threadID:" << std::this_thread::get_id() << endl;
std::future<int> fut = async(std::launch::async,&A::test,&a, 11);
int nRes = fut.get();
cout << "nRes:" << nRes << endl;
system("pause");
}
结果:
所以我建议第一个参数还是使用std::launch::async
那如何让线程等待呢?使用std::launch::deferred
从结果可以看出,即使在主线程中调用get前等待了5秒,也会卡在get的地方,等待子线程执行完毕。就我个人而言,使用性并不大。
注意:如果使用了std::launch::deferred,如果没有使用get,或者wait,就不会被执行,相当于async(std::launch::deferred,&A::test,&a, 11);
白写了!