C++11 使用异步编程std::async和std::future,packaged_task

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

先说明一点:std::asyanc是std::future的高级封装, 一般我们不会直接使用std::futrue,而是使用对std::future的高级封装std::async。 下面分别说一下。

一、std::async基本用法

std::future可以从异步任务中获取结果,一般与std::async配合使用,std::async用于创建异步任务,实际上就是创建一个线程执行相应任务。

std::async就是异步编程的高级封装,封装了std::future的操作,基本上可以代替std::thread 的所有事情。

std::async的操作,其实相当于封装了std::promise、std::packaged_task加上std::thread。

 使用代码如下:

#include <future>
#include <iostream>
#include <stout/stringify.hpp>

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

int main()
{
  std::future<bool> fut = std::async(is_prime, 700020007);
  std::cout << "please wait";
  std::chrono::milliseconds span(100);
  while (fut.wait_for(span) != std::future_status::ready)
    std::cout << ".";
  std::cout << std::endl;

  bool ret = fut.get();
  std::cout << "final result: " << stringify(ret) << std::endl;
  return 0;
}

std::async会首先创建线程执行is_prime(700020007), 任务创建之后,std::async立即返回一个std::future对象。

 主线程既可使用std::future::get获取结果,如果调用过程中,任务尚未完成,则主线程阻塞至任务完成。

 主线程也可使用std::future::wait_for等待结果返回,wait_for可设置超时时间,如果在超时时间之内任务完成,则返回std::future_status::ready状态;如果在超时时间之内任务尚未完成,则返回std::future_status::timeout状态。

上面先说了通用的做法,然后我们了解一下std::future、std::promise、std::packaged_task

二、std::future说明

四、std::packaged_task用法

std::packaged_task的作用就是提供一个不同线程之间的数据同步机制,它可以存储一个函数操作,并将其返回值传递给对应的future, 而这个future在另外一个线程中也可以安全的访问到这个值。

示例代码:

https://www.cnblogs.com/moodlxs/p/10111601.html

#if 0


//https://www.cnblogs.com/moodlxs/p/10111601.html


// packaged_task example
#include <iostream>     // std::cout
#include <future>       // std::packaged_task, std::future
#include <chrono>       // std::chrono::seconds
#include <thread>       // std::thread, std::this_thread::sleep_for

// count down taking a second for each value:
int countdown(int from, int to) {
    for (int i = from; i != to; --i) {
        std::cout << i << '\n';
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    std::cout << "Lift off!\n";
    return from - to;
}

int main()
{
    std::packaged_task<int(int, int)> tsk(countdown);   // set up packaged_task
    std::future<int> ret = tsk.get_future();            // get future

    std::thread th(std::move(tsk), 10, 0);   // spawn thread to count down from 10 to 0

    // ...

    int value = ret.get();                  // wait for the task to finish and get result

    std::cout << "The countdown lasted for " << value << " seconds.\n";

    th.join();

    return 0;
}

#elif 1

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

class myClass
{
public:
    bool test(int x) { 
        std::cout << "x: " << x << std::endl;
        return true; 
    }
};

int main()
{
    //myClass的一个实例
    myClass obj;

    //利用std::bind绑定类的成员函数
    auto func = std::bind(&myClass::test, obj, 1);
    //构造future对象
    std::future<bool> fut = std::async(std::launch::async, func);
    std::cout << "please wait";
    std::chrono::milliseconds span(100);
    while (fut.wait_for(span) != std::future_status::ready)
        std::cout << ".";
    std::cout << std::endl;
    bool rtn = fut.get();
    std::cout << "final result: " << rtn << std::endl;
    return 0;
}


#elif 0


// promise example
#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future

void print_int(std::future<int>& fut) {
    int x = fut.get();
    std::cout << "value: " << x << '\n';
}

int main()
{
    std::promise<int> prom;                      // create promise

    std::future<int> fut = prom.get_future();    // engagement with future

    std::thread th1(print_int, std::ref(fut));  // send future to new thread

    prom.set_value(10);                         // fulfill promise
                                                 // (synchronizes with getting the future)
    th1.join();
    return 0;
}


#elif 0


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

int fun(std::string x2) {
    /*x++;
    x *= 10;*/
    int x = 0;
    std::cout << std::this_thread::get_id() << std::endl;
    return x;
}


int main()
{
    // std::launch::deferred 当执行到fu.get才开始创建线程
 //   std::future<int> fu = std::async(std::launch::deferred, fun, 1);
    std::future<int> fu = std::async(std::launch::async, fun, "ni");
    
    std::cout << fu.get() << std::endl;
    std::cout << std::this_thread::get_id() << std::endl;
    return 0;
}

#elif 0
#include <iostream>
#include <future>
#include <thread>

int fun(int x) {
    x++;
    x *= 10;
    std::cout << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(5));
    return x;
}


int main()
{
    std::packaged_task<int(int)> pt(fun);         // 将函数打包起来
    std::future<int> fu = pt.get_future();        // 并将结果返回给future
    std::thread t(std::ref(pt), 1);
    std::cout << fu.get() << std::endl;
    std::cout << std::this_thread::get_id() << std::endl;
    t.join();
    return 0;
}

#endif

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值