std::async 异步任务

适用场景:

5ms一张图,分析图中是否有三角形、圆形、正方形。如果有,给出目标的最小外接矩形位置,展示出带框的图像。

场景分析:

5ms内完成3个任务(三角形算法函数、圆形算法函数、正方形算法函数),如果未完成或只完成一部分则此帧丢弃。如果全部完成,返回各任务的最小外接矩形位置。展示带框图像。

 

std::async简介:

c++11提供了promise、future、packaged_task来将任务传递给线程,然后等待(或不等待)结果返回。async提供了更高一级的封装,看上去就像是简单调用了一个函数。

int func(int a, int b) { return a + b; }
future<int> f = async(func, 2, 3);
int res = f.get();

std::async注意点:

async不一定会马上启动线程,通过future对象调用wait()或get()或直接在async中加入std::launch::async参数来启动线程。

get()会阻塞当前线程,直到结果可用或者抛出异常。

async(std::launch::deferred, ...),如果不调用future对象的get()或wait(),则线程不会启动,相当于推迟的执行。

async不一定是一个线程来完成任务。

 

demo

#include <iostream>
#include <future>

int funcSum(int a, int b)
{
    return a+b;
}

std::future<int> taskSum;  //在线程中异步执行任务(函数)

int main() {
    taskSum=std::async(std::launch::async,funcSum,2,3);     //函数立即执行
    //std::this_thread::sleep_for(std::chrono::seconds(1));
    std::future_status status=taskSum.wait_for(std::chrono::seconds(0));    //判断函数是否执行完毕(非阻塞方式)。若想阻塞,则taskSum.wait()
    if (status==std::future_status::ready)  //三种结果:未启动,逾期,已完成
    {
        int res=taskSum.get();
        std::cout << res << std::endl;
    }
    else
    {
        std::cout<<"太忙了,本次丢弃"<<std::endl;
    }

    return 0;
}

 参考

【C++】任务通信:promise和future

C++11 promise、future和async - 简讯 - 博客园

posted @ 2025-02-21 19:07  夕西行  阅读(74)  评论(0)    收藏  举报