Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wake a C++ 11 thread periodically?

I would be grateful for some pointers on how to wake a C++ 11 thread periodically (say every 100ms). The platform is Linux and the language C++. I came across this solution:

C++ 11: Calling a C++ function periodically

but there they call a callback function and then sleep for the timer interval. That means that the actual period is the function execution time + the interval. I want to call the callback at a constant interval, irrespective of its execution time.

I wonder if Boost would help? But I would prefer not to use it, as 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++ thread is a way forward? I'm not sure exactly how that would work.

Any suggestions as to how to get started would be appreciated.

like image 683
DavidA Avatar asked Jun 14 '16 12:06

DavidA


1 Answers

Use std::this_thread::sleep_until(), incrementing the absolute wakeup time by the fixed interval each time.

like image 200
Jeremy Avatar answered Oct 04 '22 14:10

Jeremy