C++11 异步编程之std::async和std::future

C++11中提供的异步任务高级抽象,包含在 < future>头文件中,它能让我们方便的实现异步地执行一个耗时任务,并在需要的时候获取其结果。
我举几个例子:
1.批量拷贝/下载文件;
2.进行一个复杂的计算;
3.执行多个嵌套的SQL查询语句;
在实际开发中,计算机进行这些操作的时候,都需要在一定时间后才能返回结果,这个时候就需要我们用异步。比起直接使用std::thread 相比,std::async和std::future有以下优势:
1.std::async 返回的future对象,可以方便地等待callable对象执行完成并获取其返回值;
2.能从实现库的一些高级功能中获益,比如线程池等,并大大减少异常的产生。
我们来看下实际代码例子future

#include <iostream>
#include <future>
#include <chrono>

bool is_prime(int x)
{
    for(int i=2;i<x;i++)
    {
        if(x%i==0)
            return false;

        return true;
    }
}

int main()
{
    std::future <bool> fut = std::async(is_prime,4444444444444444443);

    std::cout<<"wait,Checking";
    std::chrono::milliseconds span(10);
    while(fut.wait_for(span)==std::future_status::timeout)
        std::cout<<'.'<<std::flush;
        bool x = fut.get();
        std::cout<<"\n4444444444444444443"<<(x?" is":"is not") << " prime.\n";
        return 0;
}

std::future 可以用来获取异步任务的结果,因此可以把它当成一种简单的线程间同步的手段。std::future 通常由某个 Provider 创建,你可以把 Provider 想象成一个异步任务的提供者,Provider 在某个线程中设置共享状态的值,与该共享状态相关联的 std::future 对象调用 get(通常在另外一个线程中) 获取该值,如果共享状态的标志不为 ready,则调用 std::future::get 会阻塞当前的调用者,直到 Provider 设置了共享状态的值(此时共享状态的标志变为 ready),std::future::get 返回异步任务的值或异常(如果发生了异常)。
函数async()用法很像thread,同样可以启动一个线程,但该函数返回的是一个future对象而非thread对象,因此它的侧重点在于计算结果而非过程。接下来看下thread代码和async代码之间的转换:

#include <iostream>
#include <thread>
#include <future>

using namespace std;

int main(int argc, char const *argv[]) {


    thread t([]{cout<<"hello"<<endl;});
    t.join();

    return 0;
}

上面的代码等同于:

#include <iostream>
#include <thread>
#include <future>

using namespace std;


int main(int argc, char const *argv[]) {

    auto f =async([]{cout<<"hello"<<endl;});
    f.wait();

    return 0;
}

参考:
C++11 并发指南四( 详解三 std::future & std::shared_future)

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,C++ 11 引入了 std::async 函数,可以用它来创建异步任务。std::async 函数的原型如下所示: ```c++ template <class Function, class... Args> std::future<typename std::result_of<Function(Args...)>::type> async(Function&& f, Args&&... args); ``` std::async 函数的作用是创建一个异步任务,并返回一个 std::future 对象,用于获取异步任务的返回值。std::async 函数的第一个参数是要执行的函数,后面的参数是该函数的参数。该函数会在一个新线程中执行,并在执行完成后返回结果。如果该函数抛出异常,则 std::future 对象中会保存该异常信息。 std::async 函数还可以指定执行策略,例如 std::launch::async 表示在新线程中执行异步任务,std::launch::deferred 表示在调用 std::future::get() 函数时执行异步任务。如果不指定执行策略,则由编译器自行决定。 以下是一个使用 std::async 函数创建异步任务的示例: ```c++ #include <iostream> #include <future> int foo(int x) { std::cout << "foo is running in thread " << std::this_thread::get_id() << std::endl; return x + 1; } int main() { std::future<int> result = std::async(std::launch::async, foo, 1); std::cout << "main is running in thread " << std::this_thread::get_id() << std::endl; std::cout << "result is " << result.get() << std::endl; return 0; } ``` 在上面的示例中,使用 std::async 函数创建了一个异步任务 foo,并将参数 1 传递给该函数。执行结果会保存在 std::future 对象中,可以使用 std::future::get() 函数获取异步任务的返回值。在主线程中也输出了一些信息,用于对比异步任务和主线程中的执行情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值