Namespaces
Variants

std:: future

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
future
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
定义于头文件 <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 并返回它
(公开成员函数)
获取结果
返回结果
(公开成员函数)
状态
检查 future 是否拥有共享状态
(公开成员函数)
等待结果变为可用
(公开成员函数)
等待结果,若在指定的超时时间内结果不可用则返回
(公开成员函数)
等待结果,若在到达指定时间点时结果仍不可用则返回
(公开成员函数)

示例

#include <future>
#include <iostream>
#include <thread>
int main()
{
    // 来自 packaged_task 的 future
    std::packaged_task<int()> task([]{ return 7; }); // 包装函数
    std::future<int> f1 = task.get_future(); // 获取 future
    std::thread t(std::move(task)); // 在线程上启动
    // 来自 async() 的 future
    std::future<int> f2 = std::async(std::launch::async, []{ return 8; });
    // 来自 promise 的 future
    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
        {
            // 可能抛出异常的代码
            throw std::runtime_error("Example");
        }
        catch (...)
        {
            try
            {
                // 将抛出的任何内容存储到 promise 中
                p.set_exception(std::current_exception());
            }
            catch (...) {} // set_exception() 也可能抛出异常
        }
    });
    try
    {
        std::cout << f.get();
    }
    catch (const std::exception& e)
    {
        std::cout << "来自线程的异常: " << e.what() << '\n';
    }
    t.join();
}

输出:

来自线程的异常: Example

参见

(C++11)
异步运行函数(可能在新线程中)并返回持有结果的 std::future
(函数模板)
等待被异步设置的值(可能被其他 future 对象引用)
(类模板)