名稱空間
變體
操作

std::future

來自 cppreference.com
< cpp‎ | thread
 
 
併發支援庫
執行緒
(C++11)
(C++20)
this_thread 名稱空間
(C++11)
(C++11)
(C++11)
協同取消
互斥
(C++11)
通用鎖管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
條件變數
(C++11)
訊號量
門閂和屏障
(C++20)
(C++20)
期值
(C++11)
future
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危險指標
原子型別
(C++11)
(C++20)
原子型別的初始化
(C++11)(C++20 中已棄用)
(C++11)(C++20 中已棄用)
記憶體排序
(C++11)(C++26 中已棄用)
原子操作的自由函式
原子標誌的自由函式
 
 
在標頭檔案 <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::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
(函式模板) [編輯]
等待一個非同步設定的值(可能被其他 future 引用)
(類模板) [編輯]