Skip to content

std::future<T>::wait_for does not wait and returns timeout for large timeout_durations #59268

Open
@wAuner

Description

@wAuner

Related: #59260

std::future<T>::wait_for behaves incorrectly if it is provided with a large value for timeout_duration. Instead of waiting, it returns immediately and returns std::future_status::timeout.

Example 1 comparing GCC, Clang and MSVC implementation, only MSVC behaves as expected

#include <iostream>
#include <chrono>
#include <limits>
#include <future>
 
using namespace std::chrono_literals;
 
int main()
{
    std::promise<void> p;
    std::future<void> f = p.get_future();
    
    std::thread t ([&p]() {
        std::this_thread::sleep_for(2s);
        p.set_value();
    });

    // changing limit to int or a small value works as expected
    auto longWait = std::numeric_limits<long>::max();
    auto status = f.wait_for(std::chrono::milliseconds{longWait});
 
    if (status == std::future_status::timeout)
        std::cout << "timeout occurred\n";
    else if (status == std::future_status::ready)
        std::cout << "ready, no timeout occurred\n";
    
    t.join();
}

Example 2 comparing GCC, Clang and MSVC implementation, only MSVC behaves as expected

#include <iostream>
#include <chrono>
#include <limits>
#include <future>
 
using namespace std::chrono_literals;

void worker_thread()
{
    std::this_thread::sleep_for(2s);
}
 
int main()
{
    std::future<void> f = std::async(std::launch::async, worker_thread);

    // changing limit to int or a small value works as expected
    auto longWait = std::numeric_limits<long>::max();
    auto status = f.wait_for(std::chrono::milliseconds{longWait});
 
    if (status == std::future_status::timeout)
        std::cout << "timeout occurred\n";
    else if (status == std::future_status::ready)
        std::cout << "ready, no timeout occurred\n";
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    libc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.threadingissues related to threading

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions