C++11中std::async的使用詳解
C++11中的std::async是個(gè)模板函數(shù)。std::async異步調(diào)用函數(shù),在某個(gè)時(shí)候以Args作為參數(shù)(可變長參數(shù))調(diào)用Fn,無需等待Fn執(zhí)行完成就可返回,返回結(jié)果是個(gè)std::future對(duì)象。Fn返回的值可通過std::future對(duì)象的get成員函數(shù)獲取。一旦完成Fn的執(zhí)行,共享狀態(tài)將包含F(xiàn)n返回的值并ready。
std::async有兩個(gè)版本:
1.無需顯示指定啟動(dòng)策略,自動(dòng)選擇,因此啟動(dòng)策略是不確定的,可能是std::launch::async,也可能是std::launch::deferred,或者是兩者的任意組合,取決于它們的系統(tǒng)和特定庫實(shí)現(xiàn)。
2.允許調(diào)用者選擇特定的啟動(dòng)策略。
std::async的啟動(dòng)策略類型是個(gè)枚舉類enum class launch,包括:
1. std::launch::async:異步,啟動(dòng)一個(gè)新的線程調(diào)用Fn,該函數(shù)由新線程異步調(diào)用,并且將其返回值與共享狀態(tài)的訪問點(diǎn)同步。
2. std::launch::deferred:延遲,在訪問共享狀態(tài)時(shí)該函數(shù)才被調(diào)用。對(duì)Fn的調(diào)用將推遲到返回的std::future的共享狀態(tài)被訪問時(shí)(使用std::future的wait或get函數(shù))。
參數(shù)Fn:可以為函數(shù)指針、成員指針、任何類型的可移動(dòng)構(gòu)造的函數(shù)對(duì)象(即類定義了operator()的對(duì)象)。Fn的返回值或異常存儲(chǔ)在共享狀態(tài)中以供異步的std::future對(duì)象檢索。
參數(shù)Args:傳遞給Fn調(diào)用的參數(shù),它們的類型應(yīng)是可移動(dòng)構(gòu)造的。
返回值:當(dāng)Fn執(zhí)行結(jié)束時(shí),共享狀態(tài)的std::future對(duì)象準(zhǔn)備就緒。std::future的成員函數(shù)get檢索的值是Fn返回的值。當(dāng)啟動(dòng)策略采用std::launch::async時(shí),即使從不訪問其共享狀態(tài),返回的std::future也會(huì)鏈接到被創(chuàng)建線程的末尾。在這種情況下,std::future的析構(gòu)函數(shù)與Fn的返回同步。
std::future介紹參考:http://www.dbjr.com.cn/article/179229.htm
詳細(xì)用法見下面的測(cè)試代碼,下面是從其他文章中copy的測(cè)試代碼,部分作了調(diào)整,詳細(xì)內(nèi)容介紹可以參考對(duì)應(yīng)的reference:
#include "future.hpp" #include <iostream> #include <future> #include <chrono> #include <utility> #include <thread> #include <functional> #include <memory> #include <exception> #include <numeric> #include <vector> #include <cmath> #include <string> #include <mutex> namespace future_ { /////////////////////////////////////////////////////////// // reference: http://www.cplusplus.com/reference/future/async/ int test_async_1() { auto is_prime = [](int x) { std::cout << "Calculating. Please, wait...\n"; for (int i = 2; i < x; ++i) if (x%i == 0) return false; return true; }; // call is_prime(313222313) asynchronously: std::future<bool> fut = std::async(is_prime, 313222313); std::cout << "Checking whether 313222313 is prime.\n"; // ... bool ret = fut.get(); // waits for is_prime to return if (ret) std::cout << "It is prime!\n"; else std::cout << "It is not prime.\n"; return 0; } /////////////////////////////////////////////////////////// // reference: http://www.cplusplus.com/reference/future/launch/ int test_async_2() { auto print_ten = [](char c, int ms) { for (int i = 0; i < 10; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); std::cout << c; } }; std::cout << "with launch::async:\n"; std::future<void> foo = std::async(std::launch::async, print_ten, '*', 100); std::future<void> bar = std::async(std::launch::async, print_ten, '@', 200); // async "get" (wait for foo and bar to be ready): foo.get(); // 注:注釋掉此句,也會(huì)輸出'*' bar.get(); std::cout << "\n\n"; std::cout << "with launch::deferred:\n"; foo = std::async(std::launch::deferred, print_ten, '*', 100); bar = std::async(std::launch::deferred, print_ten, '@', 200); // deferred "get" (perform the actual calls): foo.get(); // 注:注釋掉此句,則不會(huì)輸出'**********' bar.get(); std::cout << '\n'; return 0; } /////////////////////////////////////////////////////////// // reference: https://en.cppreference.com/w/cpp/thread/async std::mutex m; struct X { void foo(int i, const std::string& str) { std::lock_guard<std::mutex> lk(m); std::cout << str << ' ' << i << '\n'; } void bar(const std::string& str) { std::lock_guard<std::mutex> lk(m); std::cout << str << '\n'; } int operator()(int i) { std::lock_guard<std::mutex> lk(m); std::cout << i << '\n'; return i + 10; } }; template <typename RandomIt> int parallel_sum(RandomIt beg, RandomIt end) { auto len = end - beg; if (len < 1000) return std::accumulate(beg, end, 0); RandomIt mid = beg + len / 2; auto handle = std::async(std::launch::async, parallel_sum<RandomIt>, mid, end); int sum = parallel_sum(beg, mid); return sum + handle.get(); } int test_async_3() { std::vector<int> v(10000, 1); std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) << '\n'; X x; // Calls (&x)->foo(42, "Hello") with default policy: // may print "Hello 42" concurrently or defer execution auto a1 = std::async(&X::foo, &x, 42, "Hello"); // Calls x.bar("world!") with deferred policy // prints "world!" when a2.get() or a2.wait() is called auto a2 = std::async(std::launch::deferred, &X::bar, x, "world!"); // Calls X()(43); with async policy // prints "43" concurrently auto a3 = std::async(std::launch::async, X(), 43); a2.wait(); // prints "world!" std::cout << a3.get() << '\n'; // prints "53" return 0; } // if a1 is not done at this point, destructor of a1 prints "Hello 42" here /////////////////////////////////////////////////////////// // reference: https://thispointer.com/c11-multithreading-part-9-stdasync-tutorial-example/ int test_async_4() { using namespace std::chrono; auto fetchDataFromDB = [](std::string recvdData) { // Make sure that function takes 5 seconds to complete std::this_thread::sleep_for(seconds(5)); //Do stuff like creating DB Connection and fetching Data return "DB_" + recvdData; }; auto fetchDataFromFile = [](std::string recvdData) { // Make sure that function takes 5 seconds to complete std::this_thread::sleep_for(seconds(5)); //Do stuff like fetching Data File return "File_" + recvdData; }; // Get Start Time system_clock::time_point start = system_clock::now(); std::future<std::string> resultFromDB = std::async(std::launch::async, fetchDataFromDB, "Data"); //Fetch Data from File std::string fileData = fetchDataFromFile("Data"); //Fetch Data from DB // Will block till data is available in future<std::string> object. std::string dbData = resultFromDB.get(); // Get End Time auto end = system_clock::now(); auto diff = duration_cast <std::chrono::seconds> (end - start).count(); std::cout << "Total Time Taken = " << diff << " Seconds" << std::endl; //Combine The Data std::string data = dbData + " :: " + fileData; //Printing the combined Data std::cout << "Data = " << data << std::endl; return 0; } } // namespace future_
GitHub:https://github.com/fengbingchun/Messy_Test
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
c語言結(jié)構(gòu)體字節(jié)對(duì)齊的實(shí)現(xiàn)方法
在c語言的結(jié)構(gòu)體里面一般會(huì)按照某種規(guī)則去進(jìn)行字節(jié)對(duì)齊。本文就來介紹一下如何實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解下2021-07-07Objective-C限制函數(shù)調(diào)用的頻率詳解
這篇文章主要給大家介紹了關(guān)于Objective-C限制函數(shù)調(diào)用的頻率的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12關(guān)于C++中菱形繼承和虛繼承的問題總結(jié)
C++的三大特性為:封裝,繼承,多態(tài)。但是在繼承中,存在一些使用方面的問題需要注意,下面這篇文章主要給大家總結(jié)介紹了關(guān)于C++中菱形繼承和虛繼承的問題,需要的朋友可以參考借鑒,下面來一起看看吧。2017-08-08利用C++模擬實(shí)現(xiàn)STL容器:list
列表是一種順序容器,它允許在序列中的任何位置執(zhí)行常量時(shí)間插入和刪除操作,并允許在兩個(gè)方向上進(jìn)行迭代。本文將利用C++模擬實(shí)現(xiàn)list,希望對(duì)大家有所幫助2022-12-12