kingsmasher1 kingsmasher1 - 29 days ago 6
Linux Question

How to make a thread sleep/block for nanoseconds (or at least milliseconds)?

How can I block my thread (maybe process) for nanoseconds or maybe for a milliseconds (at least) period?

Please note that I can't use sleep, because the argument to sleep is always in seconds.

R.. R..
Answer

nanosleep or clock_nanosleep is the function you should be using (the latter allows you to specify absolute time rather than relative time, and use the monotonic clock or other clocks rather than just the realtime clock, which might run backwards if an operator resets it).

Be aware however that you'll rarely get better than several microseconds in terms of the resolution, and it always rounds up the duration of sleep, rather than rounding down. (Rounding down would generally be impossible anyway since, on most machines, entering and exiting kernelspace takes more than a microsecond.)

Also, if possible I would suggest using a call that blocks waiting for an event rather than sleeping for tiny intervals then polling. For instance, pthread_cond_wait, pthread_cond_timedwait, sem_wait, sem_timedwait, select, read, etc. depending on what task your thread is performing and how it synchronizes with other threads and/or communicates with the outside world.