曾格的github

十一、std::async深入


std::async深入理解,async 用来创建一个异步任务:

std::async()我们一般不叫创建线程(他能够创建线程),我们一般叫它创建一个异步任务。

std::async和std::thread最明显的不同,就是 async 有时候并不创建新线程。

  • 如果用std::launch::deferred 来调用async?

    延迟到调用 get() 或者 wait() 时执行,如果不调用就不会执行

  • 如果用std::launch::async来调用async?

    强制这个异步任务在新线程上执行,这意味着,系统必须要创建出新线程来运行入口函数。

  • 如果同时用 std::launch::async | std::launch::deferred 

   这里这个或者关系意味着async的行为可能是 std::launch::async 创建新线程立即执行, 也可能是 std::launch::deferred 没有创建新线程并且延迟到调用get()执行

  • 不带额外参数 std::async(mythread),只给async 一个入口函数名,此时的系统给的默认值是 std::launch::async | std::launch::deferred 和 第三点 一样,有系统自行决定异步还是同步运行。

自行决定的原则

系统资源:

std::thread()如果系统资源紧张可能出现创建线程失败的情况,如果创建线程失败那么程序就可能崩溃,而且不容易拿到函数返回值(不是拿不到)
std::async()创建异步任务。可能创建线程也可能不创建线程,并且容易拿到线程入口函数的返回值;

根据经验,一个程序中线程数量  不宜超过100~200 。

async不确定性问题的解决

不加额外参数的async调用时让系统自行决定,是否创建新线程。

std::future<int> result = std::async(mythread);

问题焦点在于这个写法,任务到底有没有被异步执行。

 1 std::future_status status = result.wait_for(std::chrono::seconds(6));
 2 //std::future_status status = result.wait_for(6s);
 3     if (status == std::future_status::timeout) {
 4         //超时:表示线程还没有执行完
 5         cout << "超时了,线程还没有执行完" << endl;
 6     }
 7     else if (status == std::future_status::ready) {
 8         //表示线程成功放回
 9         cout << "线程执行成功,返回" << endl;
10         cout << result.get() << endl;
11     }
12     else if (status == std::future_status::deferred) {
13         cout << "线程延迟执行" << endl;
14         cout << result.get() << endl;
15     }
16  
posted @ 2021-09-17 19:18  曾格  阅读(2172)  评论(0编辑  收藏  举报
Live2D