MSDN: Sleep function
A value of zero causes the thread to relinquish the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution.
The special XP case is described as follows:
Windows XP: A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution. This behavior changed starting with Windows Server 2003.
MSDN states that the reminder of the threads time slice is relinquished to any other thread of equal priority. This is somewhat meaningless because a thread of higher priority would have been scheduled prior to the thread calling Sleep(0)
and a thread with lower priority would cause the Sleep(0)
to return immediately without giving anything away. Therefore Sleep(0)
only has impact to threads of equal priority by default.
Purpose of Sleep(0)
: It triggers the scheduler to re-schedule while putting the calling thread at the end of the queue. If the queue does not have any other processes of the same priority, the call will return immediately. If there are other threads, the delay is undetermined. Note: The Windows scheduler is not a single thread, it is spread all over the OS (Details: How does a scheduler regain control when wanted?).
The detailed behavior depends on the systems timer resolution setting (How to get the current Windows system-wide timer resolution). This setting also influences the threads time slice, it varies with the system timer resolution.
The system timer resolution defines the heartbeat of the system. This causes thread quanta to have specific values. The timer resolution granularity also determines the resolution of Sleep(period)
. Consequently, the accuracy of sleep periods is determined by the systems heartbeat. However, a high resolution timer setting increases the power consumption.
A Sleep(period)
with period > 0 triggers the scheduler and prohibits scheduling of the calling thread for at least the requested period.
Consequently the calling threads time slice is interrupted. It ends immediately.
Yes, Sleep(period)
with period > 0 relinquishes CPU time to other threads (if any applicable).
(Further reading: Few words about timer resolution, How to get an accurate 1ms Timer Tick under WinXP, and Limits of Windows Queue Timers).