For instance I have next code:
void waitForResponse(const std::optional<int64_t>& ms){
std::unique_lock lk{_mtx};
_cv.wait_for(lk, std::chrono::milliseconds{ms ? *ms : 0}, []() {
return someCondition;
}
}
Is it specified in standard if I pass 0
as a duration argument? Is it equal to the next code?:
void waitForResponse(const std::optional<int64_t>& ms){
std::unique_lock lk{_mtx};
_cv.wait_for(lk, []() {
return someCondition;
}
}
Is there any overhead?
According to the working draft and C++11 standard section 32.6.3 (int the working draft), wait_for
is
Equivalent to:
return wait_until(lock, chrono::steady_clock::now() + rel_time, std::move(pred));
So when you are passing
_cv.wait_for(lk, std::chrono::milliseconds{0}, []() return someCondition;}
you are basically calling
_cv.wait_until(lk, chrono::steady_clock::now(), []() return someCondition;}
and according to the timing specifications, the function times out when chrono::steady_clock::now()
> C_t (C_t the time point passed to the wait_until
function), which will timeout (and thus return) basically immediately.
And so it is different to
_cv.wait(lk, []() {
return someCondition;
}
which will block until someCondition
is true.