1. std::async参数详述
1.1 理解
1. std::async是用来创建异步任务的。
2. std::async有两个参数:std::launch::deferred和 std::launch::async
注意
1. 对于std::thread() 如果系统资源紧张,那么创建线程可能会失败,此时执行std::thread()时整个程序可能崩溃。
2. std::async我们一般不叫创建线程(即使async能够创建线程),我们一般叫它创建一个异步任务。
3. std::async和std::thread最明显的不同,就是async有时候并不创建新线程(例如如果使用deferred,那么就会在get()的时候之间在当前线程中调用,而不是创建新线程)。
1.2 使用std::launch::deferred调用async
如果使用std::launch::deferred来调用async,延迟调用 & 不会调用新线程。延迟到future对象使用get()或wait()时才执行mythread(),否则不执行。
1.3 使用std::launch::async调用async
强制异步任务在新线程上执行。
1.4 同时使用std::launch::async和std::launch::deferred
同时使用 std::launch::deferred | std::launch::async,这里的“|”意味着调用async的行为可能是创建新线程并立即执行或者没有创建新线程并且延迟到调用result.get()才开始执行任务入口函数,两者居其一。系统会自行决定是异步还是同步方式执行。
运行结果如下:
1.5 不带额外参数,只给线程入口函数
不给参数,默认值应该是“std::launch::deferred | std::launch::async”,即和c效果一致——系统会自行决定是异步(创建新线程)还是同步(不创建新线程)方式执行。
2. std::async和std::thread的区别
对于std::thread() 如果系统资源紧张,那么创建线程可能会失败,那么执行std::thread()时整个程序可能崩溃。
而且,std:::thread创建线程的方式,如果线程返回值,想拿到这个值也不容易。
std::async创建异步任务。可能创建也可能不创建线程,并且async调用方法,并且容易拿到线程入口函数的返回值。
由于系统资源限制:
(1) 如果用std::thread创建的线程太多,则可能创建失败,系统报告异常,崩溃。
(2) 如果用std::async,一般就不会报异常不会崩溃,因为 如果系统资源紧张导致无法创建新线程的时候,std::async这种不加额外参数的调用就不会创建新线程(系统智能),而是后续谁调用了result.get(),就在get()所在的线程上执行入口函数。
如果强制一定要创建新线程,就一定要用std::launch::async,但是也就会承受“系统资源紧张时程序崩溃”的危险。
(3) 一般一个程序里,线程数量不宜超过100-200。
3. async不确定性问题的解决
不额外加参数的std::async调用,是让系统自行决定是否创建新线程。
这就有可能有些问题,比如如果系统采用了延迟执行的方式(系统为了节省资源),而程序中没有使用get(),那么这个线程压根就不会执行,那就出现问题了。
问题焦点在于这种写法,这个异步任务到底有没有被推迟执行,是哪一种执行方式呢?
这就需要用到的wait_for,通过std::future_status了解线程的状态:
#include <iostream>
#include <thread>
#include <future>
using namespace std;
int mythread()
{
cout << "mythread() start, mythread_id = " << std::this_thread::get_id() << endl;
std::chrono::seconds dura(5);
std:this_thread::sleep_for(dura);
return 1;
}
int main()
{
cout << "main thread() start, main_thread_id = " << std::this_thread::get_id() << endl;
std::future<int> result = std::async(mythread);
std::future_status status = result.wait_for(0s); // 等待0s
if (status == std::future_status::deferred)
{
cout << "因为系统资源紧张了,所以线程被延迟执行" << endl;
cout << result.get() << endl; // 线程执行
}
else
{
// 任务没有被推迟
if (status == std::future_status::ready)
{
cout << "线程成功执行完毕,返回" << endl;
cout << result.get() << endl;
}
else
{
// 超时了
cout << "线程超时,没执行完" << endl;
cout << result.get() << endl;
}
}
return 0;
}
结果:
4. 参考
C++11之std::async使用介绍_Jimmy1224的博客-优快云博客_std::sync c++