C++ async task

  最近在搞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 也可以毫无压力运行)

时间: 2024-08-27 17:08:05

C++ async task的相关文章

async task 异步消息

async 和 await 是用来定义的异步方法,async  关键字是上下文关键字,原因在于只有当它修饰方法.lambda 表达式或匿名方法时,它才是关键字. 在所有其他上下文中,都会将其解释为标识符. 如果 async 关键字修改的方法不包含 await 表达式或语句,则该方法将同步执行.方法将同步运行,直至到达其第一个 await 表达式,此时会将方法挂起,直到等待的任务完成. 但编译器警告将通知你不包含 await 的任何异步方法,因为该情况可能表示存在错误. 异步方法的返回类型: 如果

Django &amp; Celery – Easy async task processing 翻译

So, while developing a web application, there comes a time when we need to process some of the tasks in the background, perhaps asynchronously. For example, your user would upload photos and the app would post them to multiple social networks. We wou

C#中 Thread,Task,Async/Await,IAsyncResult 的那些事儿!

说起异步,Thread,Task,async/await,IAsyncResult 这些东西肯定是绕不开的,今天就来依次聊聊他们 1.线程(Thread) 多线程的意义在于一个应用程序中,有多个执行部分可以同时执行:对于比较耗时的操作(例如io,数据库操作),或者等待响应(如WCF通信)的操作,可以单独开启后台线程来执行,这样主线程就不会阻塞,可以继续往下执行:等到后台线程执行完毕,再通知主线程,然后做出对应操作! 在C#中开启新线程比较简单 static void Main(string[]

.NET(C#):await返回Task的async方法

一.  FrameWork 4.0之前的线程世界    在.NET FrameWork 4.0之前,如果我们使用线程.一般有以下几种方式: 使用System.Threading.Thread 类,调用实例方法Start()开启一个新线程,调用Abort()方法来提前终止线程. 使用System.Threading.ThreadPool类,调用静态方法QueueUserWorkItem(),将方法放入线程池队列,线程池来控制调用. 使用BeginInvoke,EndInvoke,BeginRead

C# Task中的Func, Action, Async与Await的使用

在说Asnc和Await之前,先说明一下Func和Action委托, Task任务的基础的用法 1. Func Func是一种委托,这是在3.5里面新增的,2.0里面我们使用委托是用Delegate,Func位于System.Core命名空间下,使用委托可以提升效率,例如在反射中使用就可以弥补反射所损失的性能. Action<T>和Func<T,TResult>的功能是一样的,只是Action<T>没有返类型, Func<T,T,Result>:有参数,有返

C#异步中的Task,async,await

class Program { static void Main(string[] args) { Console.WriteLine("我是主线程,线程ID:{0}", Thread.CurrentThread.ManagedThreadId); TestAsync(); Console.ReadLine(); } static async void TestAsync() { Console.WriteLine("调用GetReturnResult()之前,线程ID:{0

C#多线程和异步——Task和async/await详解

阅读目录 一.什么是异步 二.Task介绍 1 Task创建和运行 2 Task的阻塞方法(Wait/WaitAll/WaitAny) 3 Task的延续操作(WhenAny/WhenAll/ContinueWith) 4 Task的任务取消(CancellationTokenSource) 三.异步方法(async/await) 回到顶部 一.什么是异步 同步和异步主要用于修饰方法.当一个方法被调用时,调用者需要等待该方法执行完毕并返回才能继续执行,我们称这个方法是同步方法:当一个方法被调用时

小白终于弄懂了:c#从async/await到Task再到Thread

1. 怎么解决async/await的无限嵌套 public async Task MyMethodAsync() { Task<int> longRunningTask = LongRunningOperationAsync(); // independent work which doesn't need the result of LongRunningOperationAsync can be done here //and now we call await on the task

实现基于Task的异步模式

返回该系列目录<基于Task的异步模式--全面介绍> 生成方法 编译器生成 在.NET Framework 4.5中,C#编译器实现了TAP.任何标有async关键字的方法都是异步方法,编译器会使用TAP执行必要的转换从而异步地实现方法.这样的方法应该返回Task或者Task<TResult>类型.在后者的案例中,方法体应该返回一个TResult,且编译器将确保通过返回的Task<TResult>是可利用的.相似地,方法体内未经处理的异常会被封送到输出的task,造成返