国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
C++ async task
userphoto

2014.10.25

關注

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

本站僅提供存儲服務,所有內容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
C++11 并發(fā)指南四(<future> 詳解三 std::future & std::shared
【C++ STL學習與應用總結】22: 函數(shù)組合之1:如何使用std::bind (since C++11)
C 11特性:bind和function函數(shù)使用
兩萬字長文讓你徹底掌握 celery
python協(xié)程系列(五)——asyncio的核心概念與基本架構
深入jQuery中的Callbacks()
更多類似文章 >>
生活服務
分享 收藏 導長圖 關注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服