[英]Why does std::future::wait_for not behave as expected?
#include <iostream>
#include <chrono>
#include <future>
using namespace std::literals;
int main()
{
std::promise<void> prom;
auto fut = prom.get_future();
std::cout << std::boolalpha << (
std::future_status::timeout ==
fut.wait_for(std::chrono::seconds::max())
);
}
The code should output nothing, because fut.wait_for
will wait for a very very long time.代码应该什么都不输出,因为
fut.wait_for
会等待很长时间。 However, it outputs true
in no time!但是,它很快就会输出
true
!
Why does std::future::wait_for
not behave as expected?为什么
std::future::wait_for
行为不符合预期?
This is due to overflow with the relative time calculation resulting in Undefined Behavior.这是由于相对时间计算溢出导致未定义行为。
There's nothing I've found in the standard that specifically addresses overflow with wait_for
, so we need to rely on the standard handling of overflow, which depends on the underlying types involved.我在标准中找不到任何专门解决
wait_for
溢出的内容,因此我们需要依赖溢出的标准处理,这取决于所涉及的底层类型。
std::chrono::seconds
is typedef for std::duration
, using a type that is a signed integral type of at least 35 bits . std::chrono::seconds
是std::duration
typedef ,使用的类型是至少 35 bits 的有符号整数类型。 Adding two duration values involves adding two signed integers.添加两个持续时间值涉及添加两个有符号整数。 It is Undefined Behavior when signed integer addition overflows .
当有 符号整数加法溢出时,这是未定义行为。
Therefore, the behavior is undefined when waiting for a really long time.因此,当等待很长时间时,行为是未定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.