本文聚焦 C++ 的異步任務 std::async,說明其回傳值取得、參數傳遞與執行策略三個重點。
std::async 會回傳一個 std::future 物件,持有最終計算結果。需要該值時呼叫 get(),此時線程會阻塞直到「期望」就緒,之後回傳結果:
std::future<int> answer = std::async([] {
int sum = 0;
for (int i = 1; i <= 100; i++)
sum += i;
std::this_thread::sleep_for(std::chrono::seconds(1)); // 增加延遲
return sum;
});
std::cout << "answer is: " << answer.get() << std::endl; // 阻塞直到返回
std::cout << "tag 2" << std::endl;
std::async 允許傳入額外參數。若第一個參數是指向成員函數的指標,第二個參數提供所屬類別的具體物件(可透過指標或包在 std::ref 中),其餘參數作為成員函數的引數;否則所有後續參數作為函數引數。當參數為右值時,會以移動方式轉移原始資料,因而支援「只移動」型別:
class XFun {
public:
void f(const std::string& str) { /* ... */ }
std::string g(const std::string& str) { /* ... */ }
void operator()(const std::string& str) { /* ... */ }
};
XFun x;
std::async(&XFun::f, &x, std::string("test f()"));
std::future<std::string> f2 = std::async(&XFun::g, x, std::string("test g() temp"));
std::async(std::ref(x), std::string("test operator()"));
std::async(XFun(), std::string("test operator() temp")); // 傳入臨時物件
std::cout << f2.get() << std::endl;
預設情況下 std::async 會啟動新線程完成任務,但也可指定額外的執行方式:
std::launch::deferred 指定等到 wait 或 get 被呼叫時才執行;std::launch::async 指定必須在獨立線程中執行。預設值為 std::launch::deferred | std::launch::async,由系統自行決定。
auto f3 = std::async(std::launch::deferred, [] { /* f3 called */ });
auto f4 = std::async(std::launch::async, [] { /* f4 called */ });
std::this_thread::sleep_for(std::chrono::seconds(1));
f3.wait();
透過 defered 與 async 的靈活搭配,開發者能精細控制任務的執行時機與線程行為。