I am trying to measure the duration of an API call which returns an std::future
object.
My current approach looks like this:
std::chrono::high_resolution_clock::time_point endTime, startTime = std::chrono::high_resolution_clock::now();
std::shared_future<API::response> responseFuture = API::request();
std::future_status status = responseFuture.wait_for(3s); // Some Timeout
if (status == std::future_status::ready)
endTime = std::chrono::high_resolution_clock::now();
else
// error handling
However, I'm unsure about the use of std::future::wait_for
. cppreference.com states:
This function may block for longer than timeout_duration due to scheduling or resource contention delays.
I am not worried about blocking longer than timeout_duration, but I do require wait_for
to immediately return once the std::future
object is available, i.e. not having an implementation along the lines of
while(!ready){
std::this_thread::sleep_for(10ms);
}
Is this guaranteed?
You are working in a preemptive multithreading environment; nothing happens "immediately". Once you give your timeslice over to the OS by blocking (or it steals your timeslice), you've given up control. The OS will unblock your thread at some point after the mutex is unlocked. OS's try to be prompt about these things, but there are no guarantees.
The best you can hope for is "soon after".
wait_for
will get you that.