3

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?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Igor
  • 1,029
  • 9
  • 21
  • 4
    Haven't peeked into the standard, but [cppreference](https://en.cppreference.com/w/cpp/thread/condition_variable/wait_for) doesn't mention any specific behaviour. So we need to assume that timeout elapses immediately. Then `wait_for` requires a duration argument, so I assume you intended `wait` in second example. Under this assumption, both examples behave entirely differently, `wait` possibly waiting forever... – Aconcagua Oct 23 '19 at 06:52
  • @Aconcagua You are totally right. Thank you. – Igor Oct 23 '19 at 07:04

1 Answers1

4

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.

Mike van Dyke
  • 2,724
  • 3
  • 16
  • 31