在线文档教程
C++
线程支持 | Thread support

std::future::wait_for

STD::未来:等待[医]为

template< class Rep, class Period > std::future_status wait_for( const std::chrono::duration& timeout_duration ) const;(since C++11)

等待结果可用。块,直到指定timeout_duration已过或结果可用,以第一位为准。返回值标识结果的状态。

用一个稳定的时钟来测量持续时间。此函数的阻塞时间可能超过timeout_duration由于调度或资源争用延迟。

如果valid()== false在调用此函数之前。

参数

timeout_duration-maximum duration to block for

返回值

ConstantExplanation
future_status::deferredThe function to calculate the result has not been started yet
future_status::readyThe result is ready
future_status::timeoutThe timeout has expired

例外

任何由时钟、时间引发的异常[医]在执行%28时钟、时间点和标准库提供的持续时间期间,不要抛出%29。

注记

鼓励实现在下列情况下检测情况:valid == false在呼叫前抛出一个future_error错误条件为future_errc::no_state...

二次

#include <iostream> #include <future> #include <thread> #include <chrono> int main() { std::future<int> future = std::async(std::launch::async, [](){ std::this_thread::sleep_for(std::chrono::seconds(3) return 8; } std::cout << "waiting...\n"; std::future_status status; do { status = future.wait_for(std::chrono::seconds(1) if (status == std::future_status::deferred) { std::cout << "deferred\n"; } else if (status == std::future_status::timeout) { std::cout << "timeout\n"; } else if (status == std::future_status::ready) { std::cout << "ready!\n"; } } while (status != std::future_status::ready std::cout << "result is " << future.get() << '\n'; }

二次

可能的产出:

二次

waiting... timeout timeout ready! result is 8

二次

另见

waitwaits for the result to become available (public member function)
wait_untilwaits for the result, returns if it is not available until specified time point has been reached (public member function)

© cppreference.com

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

http://en.cppreference.com/w/cpp/线程/前途/等待[医]为