1

I

  1. do not want to use sleep function of high time resolution clock because busy sleep consumes CPU.

  2. I do not want to depend on some wake up call spurious or signal based on some event using a conditional variable as it does not guarantee periodicity.

Please suggest if there is something on these lines possible. I cant find any solution online. I need to implement an eviction policy in a thread which will try to wake up every x seconds and clean up a queue if larger than a particular size.

Anand Kulkarni
  • 395
  • 1
  • 2
  • 10
  • Calling a function periodically in C++11: [Here](https://stackoverflow.com/a/30425945/706055). – Amit G. Jul 23 '18 at 15:08
  • Possible duplicate of [C++ 11: Calling a C++ function periodically](https://stackoverflow.com/questions/30425772/c-11-calling-a-c-function-periodically) – Andrew Henle Jul 23 '18 at 15:14

1 Answers1

1

What operating system are you running? Because on Linux/GCC5.4 at least, the std::this_thread::sleep_for function does not busy-wait. As an example:

$ cat test.txt
#include <chrono>
#include <thread>

int main(int argc, char** argv)
{
    printf("Start\n");
    std::this_thread::sleep_for(std::chrono::seconds(5));
    printf("Stop\n");
    return 0;
}

$ g++ -std=c++14 -o test test.cpp

$ time ./test

Start
Stop

real    0m5.003s
user    0m0.002s
sys     0m0.001s

See how the program took 5 seconds of real time, but almost no user(cpu) time?

As to your second point, no consumer operating system will be able to guarantee periodicity, since it is a time-sharing operating system and the underlying scheduler does not guarantee a maximum wait-time after a process becomes runnable. For that you would need to look at a real-time operating system. However, for most applications you'll probably be fine with the jitter introduced by the scheduler when using condition_variable waits.

Paul Belanger
  • 2,354
  • 14
  • 23
  • Paul Belanger , Actually you are right , but in one of my interviews the interviewer did not agree that busy sleep does not consume the CPU. This is why i was wondering because with spurious wake up the gurantee of a wake up exactly and periodically is impossible. – Anand Kulkarni Jul 25 '18 at 02:51
  • Busy sleep does consume CPU, but using `std::this_thread::sleep_*` is not a busy wait. A busy wait would be something like `auto start = clock::now(); while(clock::now() - start < wait_time){}`. Not calling sleep, but instead just spinning a loop until the time runs out. – Paul Belanger Jul 25 '18 at 13:17