最近在搞Android 開發(fā),里面多線程的使用比較頻繁,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 參數(shù)用來指定異步任務及其參數(shù)。另外,std::async() 返回一個 std::future 對象,通過該對象可以獲取異步任務的值或異常(如果異步任務拋出了異常)。
上面兩組 std::async() 的不同之處是第一類 std::async 沒有指定異步任務(即執(zhí)行某一函數(shù))的啟動策略(launch policy),而第二類函數(shù)指定了啟動策略,詳見 std::launch 枚舉類型,指定啟動策略的函數(shù)的 policy 參數(shù)可以是 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 也可以毫無壓力運行)