在C++中,std::async
是一個用于異步編程的工具,它允許你在一個單獨的線程中執行任務,并返回一個 std::future
對象,通過這個對象可以獲取任務的結果或者檢查任務的狀態。
基本用法1
lambda 表達式
#include <iostream>
#include <future>
#include <chrono>int main() {// 使用 std::async 創建一個異步任務auto future_result = std::async(std::launch::async, []{std::cout << "Task is running in a separate thread." << std::endl;std::this_thread::sleep_for(std::chrono::seconds(2));return 42; // 返回值});// 主線程繼續執行其他操作std::cout << "Main thread continues to execute." << std::endl;// 等待異步任務完成并獲取結果int result = future_result.get();std::cout << "Result from async task: " << result << std::endl;return 0;
}
解釋
std::launch::async
: 強制任務在獨立的線程中運行。std::launch::deferred
: 延遲執行任務,直到調用future::get()
或future::wait()
。std::launch::async | std::launch::deferred
: 允許實現選擇如何執行任務(默認行為)。
基本用法2
基本函數及傳入函數值
#include <iostream>
#include <future>
#include <chrono>// 定義一個簡單的異步函數
int calculate(int x) {std::this_thread::sleep_for(std::chrono::seconds(2)); // 模擬耗時操作return x * x; // 返回平方值
}int main() {// 使用 std::async 啟動異步任務auto future_result = std::async(std::launch::async, calculate, 5);// 主線程繼續執行其他操作std::cout << "Main thread continues to execute." << std::endl;// 等待異步任務完成并獲取結果try {int result = future_result.get(); // 獲取異步任務的返回值std::cout << "Result from async task: " << result << std::endl;} catch (const std::exception& e) {std::cerr << "Exception caught: " << e.what() << std::endl;}return 0;
}
輸出示例
Main thread continues to execute.
Task is running in a separate thread.
Result from async task: 25
解釋
- 異步函數定義:
calculate
是一個普通的函數,接受一個整數參數并返回其平方值。 - 啟動異步任務: 使用
std::async
啟動異步任務,傳入calculate
函數及其參數5
。 - 主線程繼續執行: 在等待異步任務完成的同時,主線程可以繼續執行其他操作。
- 獲取結果: 使用
future_result.get()
等待異步任務完成并獲取返回值。
特點
- 線程管理:
std::async
自動管理線程生命周期,簡化了多線程編程。 - 結果獲取: 可以通過
std::future
獲取異步任務的結果。 - 異常處理: 如果異步任務拋出異常,可以通過
std::future
的get()
方法捕獲。
注意事項
-
std::async
并不保證一定創建新線程,具體行為取決于實現和參數設置。 -
使用
std::future
的get()
方法可能會阻塞當前線程,直到異步任務完成。 -
異常處理: 如果異步任務拋出異常,
future::get()
會重新拋出該異常,因此建議使用try-catch
塊來捕獲異常。 -
線程安全: 如果多個線程訪問共享資源,確保采取適當的同步措施。