简体   繁体   中英

0 as a timeout in std::condition_variable::wait_for

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 section32.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM