0

I'm using std::condition_variable::wait_for(), and the maximum amount in ms to wait for is 30ms, but i noticed that the wait time is much longer than that. This is how I use the wait_for:

std::chrono::milliseconds timeToWait(30);
std::unique_lock<std::mutex> lck(mMutex);
std::chrono::high_resolution_clock::duration timeToWaitDuration(timeToWait);
auto t1 = std::chrono::high_resolution_clock::now();
std::cv_status cvStatus = mCondVar.wait_for(lck, timeToWaitDuration);
auto t2 = std::chrono::high_resolution_clock::now();
LOGI(0, "Waited for %d ms", std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1));

Possible output:

Waited for 102 ms

Waited for 159 ms

Waited for 181 ms

How is it possible? Shouldn't the thread be awaken when the time ends? Thanks.

Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
  • 2
    The timeout is the *minimal* amount of time the thread will wait, not the *exact* amount of time. If you have many other threads, they may have work to do and your thread will need to wait for its turn even after the timeout has passed. If you run this code in a single thread, you are likely to see 30 ms every time. – n. m. could be an AI Aug 15 '21 at 13:28
  • What compiler, OS? – rustyx Aug 15 '21 at 13:36
  • 30ms may be below the timer resolution . See [sleeps too long](https://stackoverflow.com/questions/58436872/stdthis-threadsleep-for-sleeps-for-too-long) – Raymond Chen Aug 15 '21 at 13:45

0 Answers0