4

I'm trying to use wait_for function of std::condition_variable compiled with Visual C++ 2017 however it returns random unexpected results with the following simple code (which never signals the variable, so it's supposed to always return timeout):

condition_variable m_cv;
mutex m_mutex;

void ThreadProc()
{
   while (1)
   {
      unique_lock<mutex> lk(m_mutex);
      cv_status r = m_cv.wait_for(lk, chrono::milliseconds(200));

      printf("Result %s\n", r == cv_status::timeout ? "timeout" : "no timeout");

      Sleep(100);
   }
}

int _tmain(int argc, _TCHAR* argv[])
{
   thread th(ThreadProc);
   th.join();

   return 0;
}

The results are random like:

Result no timeout
Result timeout
Result no timeout
Result timeout
Result timeout
Result timeout
Result timeout
Result no timeout

Am I doing something wrong or this is a compiler bug?

7
  • 3
    "...It may also be unblocked spuriously...." see note to (1), try using (2) from: en.cppreference.com/w/cpp/thread/condition_variable/wait_for Commented May 25, 2018 at 4:59
  • Hmm, that seems ridiculous, then what's the point of this function? :) Commented May 25, 2018 at 5:02
  • 1
    The point of the function is to wait for a condition to become true. You use it inside a loop that repeats the wait until the condition is true. That guards against spurious wake-ups. Commented May 25, 2018 at 6:52
  • The point is to make sure it never waits longer than 200 milliseconds. Use wait_until if you want accurate regular wake-up times (still checking for spurious events). Commented May 25, 2018 at 7:27
  • I see thanks, but why isn't that check done within wait function? Why would anyone need spurious return?? Commented May 25, 2018 at 12:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.