c++11 - C++ condition variable wait_for not behaving as expected -


i having problem understanding why test case think should passing failing of time. have distilled test down condition variable , using wait_for method, testing see if indeed wait @ least long specified duration.

the test code snippet below:

test_case("condition variable test") {     std::mutex m;     std::unique_lock<std::mutex> lock(m);     std::condition_variable cv;     bool ex = false;     std::chrono::milliseconds rel_time(50);      auto start = std::chrono::steady_clock::now();      cv.wait_for(lock, rel_time, [&ex] {return(ex);});      auto end = std::chrono::steady_clock::now();      require(std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() >= rel_time.count()); } 

i expect understanding of c++11 standard should pass of time. ironically, if change clock type system clock cannot test fail.

an excerpt cplusplus.com condition_variable::wait_for method states "if pred specified (2), function blocks if pred returns false, , notifications can unblock thread when becomes true (which useful check against spurious wake-up calls). behaves if implemented as: return wait_until (lck, chrono::steady_clock::now() + rel_time, std::move(pred));"

which implies me using steady clock take reference time stamps correct clock.

i compiling using mingw environment gcc 4.8.2 compiler.

this sounds bug in vendor's implementation. don't see how test can fail.

fwiw, require statement can simplified:

require(end - start >= rel_time); 

comparisons among durations always exact.

there 1 way test, written, fail: if std::chrono::steady_clock::duration larger milliseconds, expression duration_cast<milliseconds>(end - start) result in 0ms. protect against such poor implementation add:

static_assert(std::chrono::steady_clock::duration{1} <= std::chrono::milliseconds{1},     "this steady_clock implementation has outrageously coarse duration"); 

Comments