若需非同步執行函式 doAsyncWork(),有兩種基本選擇:
std::thread 直接執行。std::async 提交任務。// 執行緒導向
std::thread t(doAsyncWork);
// 任務導向
auto fut = std::async(doAsyncWork); // fut 為 future
std::thread 無直接機制取得返回值;future::get() 輕鬆取得。doAsyncWork 拋出異常時,future::get() 會重新拋出;std::thread 會導致 std::terminate 終止程式。C++ 中「執行緒」有三種含義:
std::thread 建構失敗會拋 std::system_error,即使函式標記 noexcept 也會拋出。處理策略複雜(當前執行緒同步執行?等待現有執行緒?)。std::async 將這些問題轉交給標準庫實作者:
auto fut = std::async(doAsyncWork); // 執行緒管理責任轉移
get()/wait() 的執行緒上同步執行,自然避免過度訂閱。同步執行(呼叫端執行緒直接跑任務)可能造成負載不均。std::async 讓調度器決策。若 GUI 執行緒需嚴格回應性,可指定啟動策略:
auto fut = std::async(std::launch::async, doAsyncWork); // 強制新執行緒
任務導向覆蓋 90%+ 場景,僅以下情況適合直接用 std::thread:
std::thread::native_handle() 提供底層句柄(如設定優先權、親和性),std::future 無對應功能。std::thread 無法直接取得返回值/異常,導致程式終止風險。std::async 任務導向解決上述大多數問題,享受標準庫演進紅利。