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++20)
(C++20)
未来体
(C++11)
future
(C++11)
(C++11)
安全回收
风险指针
原子类型
(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 相反)。

目录

[编辑]成员函数

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

[编辑]示例

#include <future>#include <iostream>#include <thread>   int main(){// 来自 packaged_task 的 futurestd::packaged_task<int()> task([](){return7;});// 包装函数 std::future<int> f1 = task.get_future();// 获取 futurestd::thread t(std::move(task));// 在线程上运行   // 来自 async() 的 future std::future<int> f2 =std::async(std::launch::async, [](){return8;});   // 来自 promise 的 futurestd::promise<int> p; std::future<int> f3 = p.get_future();std::thread([&p]{ p.set_value_at_thread_exit(9);}).detach();   std::cout<<"等待..."<<std::flush; f1.wait(); f2.wait(); f3.wait();std::cout<<"完成!\n结果为: "<< f1.get()<<' '<< f2.get()<<' '<< f3.get()<<'\n'; t.join();}

输出:

等待...完成! 结果为: 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{// 可能抛出异常的代码throwstd::runtime_error("Example");}catch(...){try{// 存储 promise 中抛出的任何异常 p.set_exception(std::current_exception());}catch(...){}// set_exception() 也可能抛出异常}});   try{std::cout<< f.get();}catch(conststd::exception& e){std::cout<<"来自线程的异常: "<< e.what()<<'\n';} t.join();}

输出:

来自线程的异常: Example

[编辑]参阅

(C++11)
异步运行一个函数(有可能在新线程中执行),并返回将保有它的结果的 std::future
(函数模板)[编辑]
等待一个被异步设置的值(可能被其他未来体引用)
(类模板)[编辑]
close