一般人可能都知道C++異步操作有async這個(gè)東西。但不知道大家是否注意過,其實(shí)它有兩個(gè)坑:
- 它不一定真的會(huì)異步執(zhí)行
- 它有可能會(huì)阻塞
下面是async具體的介紹:
async是比future,packaged_task,promise更高級(jí)的東西,它是基于任務(wù)的異步操作。
通過async可以直接創(chuàng)建異步的任務(wù),返回的結(jié)果會(huì)保存在future中,不需要像packaged_task和promise那么麻煩。
關(guān)于線程操作可以優(yōu)先使用async,看一段使用代碼:
#include
#include
#include
#include
using namespace std;
int func(int in) { return in + 1; }
int main() {
auto res = std::async(func, 5);
// res.wait();
cout << res.get() << endl; // 阻塞直到函數(shù)返回
return 0;
}
使用async異步執(zhí)行函數(shù)是不是方便多啦。
async具體語法如下:
async(std::launch::async | std::launch::deferred, func, args...);
第一個(gè)參數(shù)是創(chuàng)建策略:
- std::launch::async表示任務(wù)執(zhí)行在另一線程
- std::launch::deferred表示延遲執(zhí)行任務(wù),調(diào)用get或者wait時(shí)才會(huì)執(zhí)行,不會(huì)創(chuàng)建線程,惰性執(zhí)行在當(dāng)前線程。
如果不明確指定創(chuàng)建策略,以上兩個(gè)都不是async的默認(rèn)策略,而是undefined,它是一個(gè)基于任務(wù)的程序設(shè)計(jì),內(nèi)部有一個(gè)調(diào)度器(線程池),會(huì)根據(jù)實(shí)際情況決定采用哪種策略。
若從 std::async 獲得的 std::future 未被移動(dòng)或綁定到引用,則在完整表達(dá)式結(jié)尾。
注意:std::future的析構(gòu)函數(shù)將阻塞直至異步計(jì)算完成,實(shí)際上相當(dāng)于同步操作:
std::async(std::launch::async, []{ f(); }); // 臨時(shí)量的析構(gòu)函數(shù)等待 f()
std::async(std::launch::async, []{ g(); }); // f() 完成前不開始
注意:關(guān)于async啟動(dòng)策略這里網(wǎng)上和各種書籍介紹的五花八門,這里會(huì)以cppreference為主。
有時(shí)候我們?nèi)绻胝嬲龍?zhí)行異步操作可以對(duì)async進(jìn)行封裝,強(qiáng)制使用std::launch::async策略來調(diào)用async。
template <typename F, typename... Args>
inline auto ReallyAsync(F&& f, Args&&... params) {
return std::async(std::launch::async, std::forward(f), std::forward(params)...);
}
參考資料
https://en.cppreference.com/w/cpp/thread/async
打完收工。
-
操作
+關(guān)注
關(guān)注
0文章
43瀏覽量
19095 -
C++
+關(guān)注
關(guān)注
22文章
2119瀏覽量
75379
發(fā)布評(píng)論請(qǐng)先 登錄
PCB板返修時(shí)的兩個(gè)關(guān)鍵工藝
有兩個(gè)可變零點(diǎn)、兩個(gè)固定極點(diǎn)的有源濾波器

兩個(gè)實(shí)用的串口調(diào)試助手
合并兩個(gè)排序的鏈表
如何測(cè)量兩個(gè)光源的相對(duì)強(qiáng)度?

async-backtrace使用步驟

在trait中使用 `async fn`
分享兩個(gè)STM32應(yīng)用中的實(shí)戰(zhàn)案例
如何使用兩個(gè)LED和Arduino

兩個(gè)LED和兩個(gè)按鈕的使用

如何判斷兩個(gè)鏈表是否相交,假設(shè)兩個(gè)鏈表都沒有環(huán)?

評(píng)論