Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 237
RajSanpui Avatar asked Apr 27 '11 11:04

RajSanpui


People also ask

How do you put milliseconds to sleep?

To sleep for milliseconds with this method, simply use a fractional number. To sleep for 400 milliseconds, for example, use time. sleep(0.4), use time for 60 milliseconds sleep(0.06), for example. Python's sleep() function is a part of the time package.

How long is thread sleep 1000?

For example, with thread. sleep(1000), you intended 1,000 milliseconds, but it could potentially sleep for more than 1,000 milliseconds too as it waits for its turn in the scheduler. Each thread has its own use of CPU and virtual memory.

Does sleep block the thread?

Sleep blocks all execution, but only in the thread from which you call it.

What is thread sleep 1000 in Java?

sleep in Java. Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.


1 Answers

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.

like image 150
R.. GitHub STOP HELPING ICE Avatar answered Nov 03 '22 09:11

R.. GitHub STOP HELPING ICE