Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to guarantee exact thread sleep interval?

Usually if I want to simulate some work or wait exact time interval I use condition_variable::wait_for or at the worst thread::this_thread::sleep_for. But condition_variable documentation states that wait_for or wait_until methods may block longer than was requested.

This function may block for longer than timeout_duration due to scheduling or resource contention delays.

How exact wait intervals can be guaranteed?

UPDATE

Can I reach it without condition_variable?

like image 629
Viktor Avatar asked Oct 20 '25 04:10

Viktor


1 Answers

You cannot do this.

In order to have exact guarantees like this, you need a real time operating system.

C++ does not guarantee you are on a real time operating system.

So it provides the guarantees that a typical, non-RTOS provides.

Note that there are other complications to programming on a RTOS that go far beyond the scope of this question.

In practice, one thing people when they really want fine-grained timing control (say, they are twiddling around with per-frame or per-scanline buffers or the like, or audio buffers, or whatever) do is check if the time is short, and if so spin-wait. If the time is longer, they wait for a bit less than the amount of time they want to wait for, then wake up and spin.

This is also not guaranteed to work, but works well enough for almost all cases.

On a RTOS, the platform may provide primitives like you want. These lie outside the scope of standard C++. No typical desktop OS is an RTOS that I am aware of. If you are programming for a fighter jet's control hardware or similar, you may be programming on an RTOS.

I hope you aren't writing fighter jet control software and asking this question on stack overflow.

like image 79
Yakk - Adam Nevraumont Avatar answered Oct 21 '25 18:10

Yakk - Adam Nevraumont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!