类模板std::future提供访问异步操作结果的机制: (通过std::async、std::packaged_task或std::promise创建的)异步操作能提供一个std::future对象给该异步操作的创建者。 然后,异步操作的创建者可以使用多个方法查询、等待或从std::future提取值。若异步操作尚未提供值,则这些方法可能阻塞。
(std::shared_future<T> 的公开成员函数) wait_until 等待结果,如果在已经到达指定的时间点时仍然无法得到结果,则返回。 (std::future<T> 的公开成员函数) wait_until 等待结果,如果在已经到达指定的时间点时仍然无法得到结果,则返回。 (std::shared_future<T> 的公开成员函数) 首页...
上面的最后一段话,中文含义是:注意std::future所引用的共享状态是不和任何其他异步操作所返回的future对象所共享的(与之对应的是std::shared_future) 并且异步操作创建方只能调用一次future::get来获取异步调用的结果信息,这是因为future::get函数内部,会断开future对象与关联状态对象之间的链接,如下代码行5 future对象...
()<<" launching thread\n";std::future<int>f=std::async(std::launch::async,[]{std::this_thread::sleep_for(1s);returntrue?throwstd::runtime_error("7"):7;});std::cout<<time()<<" waiting for the future, f.valid() = "<<f.valid()<<'\n';try{intn=f.get();std::cout<<...
std::future<T>::wait voidwait()const; (since C++11) Blocks until the result becomes available.valid()==trueafter the call. The behavior is undefined ifvalid()==falsebefore the call to this function. Parameters (none) Return value
std::promise - cppreference.com std::future - cppreference.com std::shared_future - cppreference.com 请注意,上述示例代码仅用于演示std::promise和std::future的基本用法,并未涉及std::shared_future。在实际应用中,你可以根据需要使用std::shared_future来共享异步操作的结果。
std::future是一种简易方便的线程间同步手段中的一环,与std::promise或者std::packaged_task配合实现简单的线程同步,由于是共享关联之中被动的一方,所以始终存在是否有效的问题,对于共享状态值的获取也需要在其标志为ready的条件下进行。 (参考网站:CSDN、cppreference.com、cplusplus.com等) ...
template<> class future<void>; (3) (since C++11) The class template std::future provides a mechanism to access the result of asynchronous operations: An asynchronous operation (created via std::async, std::packaged_task, or std::promise) can provide a std::future object to the creator...
双方持有的std::promise对象实例和std::future对象实例分别连接一个共享对象,这个共享对象在异步调用创建...
std::shared_future与std::future类似,但是shared_future允许拷贝、对future移动构造,还允许多个shared_future对同一个共享状态有效,实现一个promise或packaged_task对象关联多个shared_future对象。 2、构造函数 (1) 默认构造函数,无任何共享状态的关联。 (2) 拷贝构造函数,x的一切均被拷贝到新的shared_future对象。