peidong zhou
peidong zhou

Reputation: 1

whether std::future::wait_for uses different clock(steady clock vs system clock) depends on compiler?

When I use different compilers to compile 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;
}

When wait_for function is waiting for myfunction to be finished (wait for duration is 5000 milliseconds), I set the system clock ahead by one minute.

It seems future::wait_for has different behaviors with different compilers.

According to wait_for, The standard recommends that a steady clock is used to measure the duration. If an implementation uses a system clock instead, the wait time may also be sensitive to clock adjustments.

It looks like gcc version 10.2.0 uses system clock for future::wait_for, and gcc version 13.2.0 uses steady clock for future::wait_for.

Does this mean compiler will use a steady clock or a system clock?

Is there any compile flag to specify whether to use a steady clock or a system clock?

Upvotes: 0

Views: 102

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

Does this mean compiler will use a steady clock or a system clock?

Yes.

Is there any compile flag to specify whether to use a steady clock or a system clock?

No. I am not aware of such flag.


std::future has certain issues (mainly related to being the return type of std::async. It was even considered for deprecation if I remember correctly. todo: add reference). This seems to be another one.

Note that std::future::wait_until does allow you to choose the Clock to use. This difference might be just due to the fact that the Clock is part of the time_points type but not of a duration (the argument to wait_for). However, you can calculate the time_point from a duration for a Clock of your choice and use that with wait_until to wait for the result.

Upvotes: 0

Related Questions