std::future

定义于头文件 <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::shared_future 相反)。

目录

成员函数

构造期货对象
(公开成员函数)
析构future对象
(公开成员函数)
移动future对象
(公开成员函数)
*this 转移共享状态给 shared_future 并返回它
(公开成员函数)
获取结果
返回结果
(公开成员函数)
状态
检查 future 是否拥有共享状态
(公开成员函数)
等待结果变得可用
(公开成员函数)
等待结果,如果在指定的超时间隔后仍然无法得到结果,则返回。
(公开成员函数)
等待结果,如果在已经到达指定的时间点时仍然无法得到结果,则返回。
(公开成员函数)

示例

#include <iostream>
#include <future>
#include <thread>
 
int main()
{
    // 来自 packaged_task 的 future
    std::packaged_task<int()> task([](){ return 7; }); // 包装函数
    std::future<int> f1 = task.get_future();  // 获取 future
    std::thread(std::move(task)).detach(); // 在线程上运行
 
    // 来自 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';
}

输出:

Waiting...Done!
Results are: 7 8 9

参阅

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

版本历史

  • (当前 | 先前 2017年9月24日 (日) 07:46Fruderica讨论 | 贡献 . . (2,638字节) (+4). . (撤销)
  • 当前 | 先前 2017年9月24日 (日) 07:46Fruderica讨论 | 贡献 . . (2,634字节) (-327). . (撤销)
  • 当前 | 先前 2017年3月12日 (日) 06:35Jason n讨论 | 贡献 . . (2,961字节) (-18). . (撤销)
  • 当前 | 先前 2017年3月12日 (日) 06:09Jason n讨论 | 贡献. . (2,979字节) (-965). . (撤销)
  • 当前 | 先前 2013年7月9日 (二) 02:07P12bot讨论 | 贡献 . . (3,944字节) (+6). . (Allow search engines to index popular pages.) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:31P12bot讨论 | 贡献 . . (3,938字节) (-283). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 20:09P12bot讨论 | 贡献 . . (4,221字节) (+201). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:08P12讨论 | 贡献 . . (4,020字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (4,020字节) (+4,020). . (Translated from the English version using Google Translate)