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.
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.
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.
Sleep blocks all execution, but only in the thread from which you call it.
sleep in Java. Thread. sleep() method can be used to pause the execution of current thread for specified time in 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With