std::future::wait_for returns immediately timeout while the time duration has not elapsed

161 Views Asked by At

I have encountered an issue related to std::async and std::future::wait_for. I have the following code

auto future = std::async(std::launch::async, [&](){return myfunction();});

auto status = future.wait_for(std::chrono::milliseconds(5000));
if (status == std::future_status::ready)
{
    auto result = future.get();
    std::cout << "result is " << result << std::endl;
}
else
{
    std::cout << (status == std::future_status::timeout ? "timeout" : "deferred") << std::endl;
}

It is running on x86_64 GNU/Linux (The CXX compiler identification is GNU 13.2.0). Most of the time, this piece of code works well. However, occasionally(I only meet once), future.wait_for returned timeout immediately without waiting even if timeout_duration is set to 5seconds.

According to text, wait_for should return timeout only if timeout_duration has elapsed.

So far, I have no idea why future.wait_for returned timeout immediately without waiting occasionally.

Has anyone encountered a similar issue before?

0

There are 0 best solutions below