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

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


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.


One relatively portable way is to use select() or pselect() with no file descriptors:

void sleep(unsigned long nsec) {    struct timespec delay = { nsec / 1000000000, nsec % 1000000000 };    pselect(0, NULL, NULL, NULL, &delay, NULL);}


Try usleep(). Yes this wouldn't give you nanosecond precision but microseconds will work => miliseconds too.