C++ async task

KingsLanding發表於2014-10-12

  最近在搞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 也可以毫無壓力執行)

相關文章