How to periodically wake up a C ++ 11 stream?

I would appreciate some guidance on how to periodically wake up a C ++ 11 stream (say, every 100 ms). The platform is Linux and the C ++ language. I came across this solution:

C ++ 11: Periodically call a C ++ function

but there they call the callback function and then sleep for the timer interval. This means that the actual period is the execution time of the function + interval. I want to call a callback at a constant interval, regardless of how long it takes.

I wonder if Boost will help? But I would prefer not to use it, since this project is not multi-platform, and I want to minimize the use of third-party libraries.

Perhaps combining a POSIX timer with a C ++ stream is the way forward? I don’t know exactly how this will work.

Any suggestions on how to get started will be appreciated.

+6
source share
5 answers

Here is a good article on this topic: Periodic processing with standard C ++ 11 tools https://bulldozer00.com/2013/12/27/periodic-processing-with-standard-c11-facilities/

+4
source

Use std::this_thread::sleep_until() , increasing the absolute wake-up time by a fixed interval each time.

+6
source

You need to measure the time that your function takes to execute, and then the sleeping period, with the exception of the execution time. Use std :: this_thread :: sleep_for to sleep for the time that has passed. For instance:

 const auto timeWindow = std::chrono::milliseconds(100); while(true) { auto start = std::chrono::steady_clock::now(); do_something(); auto end = std::chrono::steady_clock::now(); auto elapsed = end - start; auto timeToWait = timeWindow - elapsed; if(timeToWait > std::chrono::milliseconds::zero()) { std::this_thread::sleep_for(timeToWait); } } 

NOTE. If your compiler supports it, you can use 100ms rather than std::chrono::milliseconds(100) . Mine does not: - (

+3
source

For a clean C ++ approach without any implementation-specific functions, you can create std::mutex and std::condition_variable , block mutexes, and then use wait_for() to sleep on a conditional, 100 ms, or any other interval in your thread.

For more precise control of wakeup intervals, which takes into account the actual runtime of your thread to execute between pauses, use wait_until() along with a suitable clock.

+1
source

I would call the function via std::async on the timer. However, if your function regularly takes longer than a period, you quickly consume resources. Also, creating a new thread has a relatively high cost.

Thus, you can specify the duration of the function duration via std::chrono::high_resolution_clock , and then use wait_for for the sleeping remainder of the period.

+1
source

All Articles