一、async
1、定義
2、啟動策略
async
函數(shù)接受兩種不同的啟動策略,這些策略在std::launch
枚舉中定義,如下:
-
std::launch::defered
:這種策略意味著任務(wù)將在調(diào)用future::get()
或future::wait
函數(shù)時延遲執(zhí)行,也就是任務(wù)將在需要結(jié)果時同步執(zhí)行 -
std::launch::async
:任務(wù)在單獨一個線程上異步執(zhí)行
默認(rèn)情況下
async
使用std::launch::defered | std::launch::async
策略,這意味著任務(wù)可能異步執(zhí)行,也可能延遲執(zhí)行,具體取決于實現(xiàn),示例:
#include <iostream>
#include <thread>
#include <future>
using namespace std;
thread::id test_async() {
this_thread::sleep_for(chrono::milliseconds(500));
return this_thread::get_id();
}
thread::id test_async_deferred() {
this_thread::sleep_for(chrono::milliseconds(500));
return this_thread::get_id();
}
int main() {
// 另起一個線程去運行test_async
future<thread::id> ans = std::async(launch::async, test_async);
// 還沒有運行test_async_deferred
future<thread::id> ans_def = std::async(launch::deferred,test_async_deferred); //還沒有運行test_async_deferred
cout << "main thread id = " << this_thread::get_id() << endl;
// 如果test_async這時還未運行完,程序會阻塞在這里,直到test_async運行結(jié)束返回
cout << "test_async thread id = " << ans.get() << endl;
// 這時候才去調(diào)用test_async_deferred,程序會阻塞在這里,直到test_async_deferred運行返回
cout << "test_async_deferred thread id = = " << ans_def.get() << endl;
return 0;
}
輸出結(jié)果文章來源:http://www.zghlxwxcb.cn/news/detail-820269.html
main thread id = 1
test_async thread id = 2
test_async_deferred thread id = = 1
Process returned 0 (0x0) execution time : 1.387 s
Press any key to continue.
從輸出結(jié)果可以看出采用
std::launch::defered
策略時任務(wù)是同步執(zhí)行,采用launch::async
策略時任務(wù)是異步執(zhí)行。文章來源地址http://www.zghlxwxcb.cn/news/detail-820269.html
到了這里,關(guān)于C++ 并發(fā)編程 | future與async的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!