std::future
來自 cppreference.com
在標頭檔案 <future> 中定義 |
||
template< class T > class future; |
(1) | (C++11 起) |
template< class T > class future<T&>; |
(2) | (C++11 起) |
template<> class future<void>; |
(3) | (C++11 起) |
類模板std::future
提供了一種訪問非同步操作結果的機制。
- 非同步操作(透過std::async、std::packaged_task或std::promise建立)可以向該非同步操作的建立者提供一個
std::future
物件。
- 非同步操作的建立者隨後可以使用各種方法來查詢、等待或從
std::future
中提取值。如果非同步操作尚未提供值,這些方法可能會阻塞。
- 當非同步操作準備好向建立者傳送結果時,它可以透過修改與建立者的
std::future
連結的共享狀態(例如std::promise::set_value)來實現。
請注意,std::future
引用的共享狀態不與任何其他非同步返回物件共享(與std::shared_future相反)。
目錄 |
[編輯] 成員函式
構造 future 物件 (公共成員函式) | |
析構 future 物件 (公共成員函式) | |
移動 future 物件 (公共成員函式) | |
將共享狀態從*this轉移到shared_future並返回它 (公共成員函式) | |
Getting the result | |
返回結果 (公共成員函式) | |
State | |
檢查 future 是否具有共享狀態 (公共成員函式) | |
等待結果可用 (公共成員函式) | |
等待結果,如果在指定的超時時間內不可用則返回 (公共成員函式) | |
等待結果,如果到指定時間點仍不可用則返回 (公共成員函式) |
[編輯] 示例
執行此程式碼
#include <future> #include <iostream> #include <thread> int main() { // future from a packaged_task std::packaged_task<int()> task([]{ return 7; }); // wrap the function std::future<int> f1 = task.get_future(); // get a future std::thread t(std::move(task)); // launch on a thread // future from an async() std::future<int> f2 = std::async(std::launch::async, []{ return 8; }); // future from a promise std::promise<int> p; std::future<int> f3 = p.get_future(); std::thread([&p]{ p.set_value_at_thread_exit(9); }).detach(); std::cout << "Waiting..." << std::flush; f1.wait(); f2.wait(); f3.wait(); std::cout << "Done!\nResults are: " << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n'; t.join(); }
輸出
Waiting...Done! Results are: 7 8 9
[編輯] 帶異常的示例
執行此程式碼
#include <future> #include <iostream> #include <thread> int main() { std::promise<int> p; std::future<int> f = p.get_future(); std::thread t([&p] { try { // code that may throw throw std::runtime_error("Example"); } catch (...) { try { // store anything thrown in the promise p.set_exception(std::current_exception()); } catch (...) {} // set_exception() may throw too } }); try { std::cout << f.get(); } catch (const std::exception& e) { std::cout << "Exception from the thread: " << e.what() << '\n'; } t.join(); }
輸出
Exception from the thread: Example
[編輯] 另請參閱
(C++11) |
非同步(可能在新執行緒中)執行一個函式並返回一個將儲存結果的std::future (函式模板) |
(C++11) |
等待一個非同步設定的值(可能被其他 future 引用) (類模板) |