最近在搞Android 開發,裏面多線程的使用比較頻繁,java多線程接口很方便。 Thread, AysncTask, Handler 這些接口比起posix提供的pthread_create()等一系列接口方便不少,想到C++11也支持方便的多線程編程,最近java中AsyncTask用的比較多,因而學習了一下C++中的async task。java
C++ std::async(),原型以下: ios
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);
ubuntu
std::async() 的 fn 和 args 參數用來指定異步任務及其參數。另外,std::async() 返回一個 std::future 對象,經過該對象能夠獲取異步任務的值或異常(若是異步任務拋出了異常)。多線程
上面兩組 std::async() 的不一樣之處是第一類 std::async 沒有指定異步任務(即執行某一函數)的啓動策略(launch policy),而第二類函數指定了啓動策略,詳見 std::launch 枚舉類型,指定啓動策略的函數的 policy 參數能夠是 launch::async,launch::deferred,以及二者的按位或( | )。異步
來一段代碼學習一下:async
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 也能夠毫無壓力運行)函數