打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C++ async task
userphoto

2014.10.25

关注

  最近在搞Android 开发,里面多线程的使用比较频繁,java多线程接口很方便。 Thread, AysncTask, Handler 这些接口比起posix提供的pthread_create()等一系列接口方便很多,想到C++11也支持方便的多线程编程,最近java中AsyncTask用的比较多,于是学习了一下C++中的async task。

  

  C++ std::async(),原型如下:  

  unspecified policy (1) 

        template <class Fn, class... Args>
          future<typename result_of<Fn(Args...)>::type> async(Fn&& fn, Args&&... args);

  specific policy (2)
        template <class Fn, class... Args>
          future<typename result_of<Fn(Args...)>::type> async(launch policy, Fn&& fn, Args&&... args);
  

      std::async() 的 fn 和 args 参数用来指定异步任务及其参数。另外,std::async() 返回一个 std::future 对象,通过该对象可以获取异步任务的值或异常(如果异步任务抛出了异常)。

  上面两组 std::async() 的不同之处是第一类 std::async 没有指定异步任务(即执行某一函数)的启动策略(launch policy),而第二类函数指定了启动策略,详见 std::launch 枚举类型,指定启动策略的函数的 policy 参数可以是 launch::async,launch::deferred,以及两者的按位或( | )。

  来一段代码学习一下:

 1 #include "stdafx.h" 2  3  4 #include <stdio.h> 5 #include <stdlib.h> 6  7 #include <cmath> 8 #include <chrono> 9 #include <future>10 #include <iostream>11 12 13 int main(int argc, const char *argv[])14 {15     auto begin = std::chrono::steady_clock::now();16 17         //std::future<double> 18     auto f(std::async(std::launch::async,[](int n){
19 std::cout << std::this_thread::get_id()20 << " start computing..." << std::endl;21 22 double ret = 0;23 for (int i = 0; i <= n; i++) {24 ret += std::sin(i);25 }26 27 std::cout << std::this_thread::get_id()28 << " finished computing..." << std::endl;29 return ret;30 }31 ,100000000));32 33 34 while(f.wait_for(std::chrono::seconds(1))35 != std::future_status::ready) {36 std::cout << "task is running...\n";37 }38 39 40 auto end = std::chrono::steady_clock::now();41 42 auto diff = end - begin;43 44 std::cout << "async_task result: "<<f.get() << std::endl;45 std::cout << std::chrono::duration <double, std::milli> (diff).count() << " ms" << std::endl;46 47 return EXIT_SUCCESS;48 }

运行结果:(VS2012,ubuntu14.04 使用的是gcc4.9.1 也可以毫无压力运行)

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C++11 并发指南四(<future> 详解三 std::future & std::shared
【C++ STL学习与应用总结】22: 函数组合之1:如何使用std::bind (since C++11)
C 11特性:bind和function函数使用
两万字长文让你彻底掌握 celery
python协程系列(五)——asyncio的核心概念与基本架构
深入jQuery中的Callbacks()
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服