C++11異步與通信之std::async的使用
概念簡(jiǎn)介
std::async 異步運(yùn)行一個(gè)函數(shù),將返回值保存在std::future中。
含有2個(gè)策略參數(shù):
- launch::deferred 延遲執(zhí)行,當(dāng)調(diào)用wait()和get()時(shí),任務(wù)才會(huì)被運(yùn)行,且不創(chuàng)建線程;
- launch::async : 創(chuàng)建線程并執(zhí)行任務(wù),默認(rèn)是此類型;
- 同樣的,調(diào)用get()方法獲取對(duì)象時(shí),也是阻塞等待的。
代碼示例
使用deferred策略
int Func() { ? ? std::cout << "Func Thread id = " << std::this_thread::get_id() << std::endl; ? ? return 0; } int main() { ?? ? ? std::cout << "Main Thread id = " << std::this_thread::get_id() << std::endl; ? ? //創(chuàng)建延遲任務(wù),這里不會(huì)啟動(dòng)新線程 ? ? auto future = std::async(std::launch::deferred, Func); ? ? //調(diào)用future.get()時(shí),才會(huì)去調(diào)用Func? ? ? //讀者可以試著把這行代碼注釋掉,你會(huì)發(fā)現(xiàn)Func函數(shù)根本沒有創(chuàng)建 ? ? std::cout << "Result = ?" << future.get() << std::endl;; ? ? //通過打印線程id我們發(fā)現(xiàn),是在同一個(gè)線程中執(zhí)行的,沒有創(chuàng)建新線程 ? ? return 0; }
執(zhí)行結(jié)果
Main Thread id = 140646835402560
Result = Func Thread id = 140646835402560
0
使用async策略
int Func(int n) { ? ? std::cout << "Func Thread id = " << std::this_thread::get_id() << std::endl; ? ? return -1; } int main() { ?? ? ? std::cout << "Main Thread id = " << std::this_thread::get_id() << std::endl; ? ? //創(chuàng)建異步任務(wù) 使用默認(rèn)策略 ?啟動(dòng)一個(gè)新線程 ? ? //并且馬上會(huì)執(zhí)行異步任務(wù)代碼 ? ? auto future = std::async(std::launch::async, Func, 100); ? ? //通過睡眠發(fā)現(xiàn),get()調(diào)用之前,任務(wù)已經(jīng)在被執(zhí)行了 ? ? std::this_thread::sleep_for(std::chrono::seconds(5)); ? ? std::cout << "Result = ?" << future.get() << std::endl;; ? ? //通過打印線程id我們發(fā)現(xiàn),不是在同一個(gè)線程中執(zhí)行的,創(chuàng)建了新線程 ? ? return 0; }
運(yùn)行結(jié)果:
Main Thread id = 140052716861248
Func Thread id = 140052716857088
Result = -1
補(bǔ)充
與std::packaged_task相比,std::async不僅可以打包一個(gè)異步任務(wù),std::launch::async策略下還可以幫忙創(chuàng)建一個(gè)新線程并執(zhí)行任務(wù),某些場(chǎng)景下比std::packaged_task方便一些。
到此這篇關(guān)于C++11異步與通信之std::async的使用的文章就介紹到這了,更多相關(guān)C++11 std::async內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Qt實(shí)現(xiàn)界面滑動(dòng)切換效果的思路詳解
這篇文章主要介紹了Qt實(shí)現(xiàn)界面滑動(dòng)切換效果,主要包括設(shè)計(jì)思路及主要函數(shù)講解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07C++靜態(tài)成員變量和靜態(tài)成員函數(shù)的使用方法總結(jié)
下面小編就為大家?guī)硪黄狢++靜態(tài)成員變量和靜態(tài)成員函數(shù)的使用方法總結(jié)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01centos 7 vscode cmake 編譯c++工程的教程詳解
這篇文章給大家介紹了centos 7 使用vscode+cmake配置簡(jiǎn)單c++項(xiàng)目的方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2020-05-05使用C++實(shí)現(xiàn)一個(gè)高效的線程池
在多線程編程中,線程池是一種常見且高效的設(shè)計(jì)模式,本文將詳細(xì)介紹如何使用C++實(shí)現(xiàn)一個(gè)線程池,并解析相關(guān)代碼實(shí)現(xiàn)細(xì)節(jié),需要的小伙伴可以參考下2024-12-12QT實(shí)戰(zhàn)之打開最近文檔功能的實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了如何利用Qt實(shí)現(xiàn)打開最近文檔功能,并實(shí)現(xiàn)基本的新建、打開、保存、退出、幫助等功能,感興趣的可以動(dòng)手嘗試一下2022-06-06