std::future
来自 cppreference.cn
定义于头文件 <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::promise::set_value)来实现,该共享状态链接到创建者的
std::future
。
请注意,std::future
引用未与其他任何异步返回对象共享的共享状态(与 std::shared_future 相对)。
内容 |
[编辑] 成员函数
构造 future 对象 (公开成员函数) | |
析构 future 对象 (公开成员函数) | |
移动 future 对象 (公开成员函数) | |
将共享状态从 *this 转移到 shared_future 并返回它 (公开成员函数) | |
获取结果 | |
返回结果 (公开成员函数) | |
状态 | |
检查 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 引用) (类模板) |