首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::future

Defined in header <future>

?

?

template< class T > class future;

(1)

(since C++11)

template< class T > class future<T&>;

(2)

(since C++11)

template<> class future<void>;

(3)

(since C++11)

类模板std::future提供访问异步操作结果的机制:

  • 创建的异步操作%28std::async,,,std::packaged_task,或std::promise%29可以提供std::future对象指定为该异步操作的创建者。
  • 然后,异步操作的创建者可以使用各种方法来查询、等待或从std::future如果异步操作尚未提供值,这些方法可能会阻塞。
  • 当异步操作准备向创建者发送结果时,可以通过修改共享状态%28等std::promise::set_value%29,链接到创建者%27 sstd::future...

请注意std::future与任何其他异步返回对象%28不共享的引用共享状态std::shared_future29%。

成员函数

(constructor)

constructs the future object (public member function)

(destructor)

destructs the future object (public member function)

operator=

moves the future object (public member function)

share

transfers the shared state from *this to a shared_future and returns it (public member function)

得到结果

GET返回结果%28公共成员函数%29

国家

有效检查未来是否具有共享状态%28公共成员函数%29

等待结果变为可用%28公共成员函数%29

等待[医]对于等待结果,如果指定的超时持续时间%28公共成员函数%29不可用,则返回

等待[医]在等待结果之前,如果指定的时间点已达到%28公共成员函数%29,则返回不可用的结果。

二次

代码语言:javascript
复制
#include <iostream>
#include <future>
#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(std::move(task)).detach(); // 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';
}

二次

产出:

二次

代码语言:javascript
复制
Waiting...Done!
Results are: 7 8 9

二次

另见

async (C++11)

runs a function asynchronously (potentially in a new thread) and returns a std::future that will hold the result (function template)

shared_future (C++11)

waits for a value (possibly referenced by other futures) that is set asynchronously (class template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com