std::shared_future<T>::wait
來自 cppreference.com
< cpp | thread | shared_future
void wait() const; |
(C++11 起) | |
阻塞直到結果可用。呼叫後 valid() == true。
若呼叫此函式前 valid
() == false,則行為未定義。
目錄 |
[edit] 引數
(無)
[edit] 返回值
(無)
[編輯] 異常
可能丟擲實現定義的異常。
[edit] 注意
鼓勵實現檢測呼叫前 valid() == false 的情況,並丟擲帶有錯誤條件 std::future_errc::no_state 的 std::future_error。
從多個執行緒對同一個 std::shared_future
呼叫 wait 不安全;預期的用法是每個等待相同共享狀態的執行緒都擁有一個 std::shared_future
的副本。
[edit] 示例
執行此程式碼
#include <chrono> #include <future> #include <iostream> #include <thread> int fib(int n) { if (n < 3) return 1; else return fib(n - 1) + fib(n - 2); } int main() { std::shared_future<int> f1 = std::async(std::launch::async, []() { return fib(40); }); std::shared_future<int> f2 = std::async(std::launch::async, []() { return fib(43); }); std::cout << "waiting... " << std::flush; const auto start = std::chrono::system_clock::now(); f1.wait(); f2.wait(); const auto diff = std::chrono::system_clock::now() - start; std::cout << std::chrono::duration<double>(diff).count() << " seconds\n"; std::cout << "f1: " << f1.get() << '\n'; std::cout << "f2: " << f2.get() << '\n'; }
可能的輸出
waiting... 1.61803 seconds f1: 102334155 f2: 433494437
[edit] 參閱
等待結果,如果在指定的超時時間內不可用則返回 (public member function) | |
等待結果,如果到指定時間點仍不可用則返回 (public member function) |