Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make thread sleep less than a millisecond on Windows

On Windows I have a problem I never encountered on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On Windows, however, there is only Sleep with millisecond granularity.

On Unix, I can use the use the select system call to create a microsecond sleep which is pretty straightforward:

int usleep(long usec) {     struct timeval tv;     tv.tv_sec = usec/1000000L;     tv.tv_usec = usec%1000000L;     return select(0, 0, 0, 0, &tv); } 

How can I achieve the same on Windows?

like image 760
Jorge Ferreira Avatar asked Sep 17 '08 16:09

Jorge Ferreira


People also ask

How do you make a 10 second thread sleep?

sleep(1000) sleeps 1000 miliseconds, which is 1 second. Make that Thread. sleep(10000) and it will sleep 10 seconds.

Is thread sleep in seconds or milliseconds?

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

How accurate is thread sleep?

Incredibly inaccurate. You have to deal with the inconsistencies of the OS process scheduler, the time spent context switching, the Java VM, etc. Well documentation is silent on its accuracy- it talks a lot about accuracy for System.


2 Answers

This indicates a mis-understanding of sleep functions. The parameter you pass is a minimum time for sleeping. There's no guarantee that the thread will wake up after exactly the time specified. In fact, threads don't "wake up" at all, but are rather chosen for execution by the OS scheduler. The scheduler might choose to wait much longer than the requested sleep duration to activate a thread, especially if another thread is still active at that moment.

like image 81
Joel Coehoorn Avatar answered Oct 02 '22 19:10

Joel Coehoorn


As Joel says, you can't meaningfully 'sleep' (i.e. relinquish your scheduled CPU) for such short periods. If you want to delay for some short time, then you need to spin, repeatedly checking a suitably high-resolution timer (e.g. the 'performance timer') and hoping that something of high priority doesn't pre-empt you anyway.

If you really care about accurate delays of such short times, you should not be using Windows.

like image 32
Will Dean Avatar answered Oct 02 '22 18:10

Will Dean