I used to see Sleep(0)
in some part of my code where some infinite/long while
loops are available. I was informed that it would make the time-slice
Sleep(0);
At that instruction, the system scheduler will check for any other runnable threads and possibly give them a chance to use the system resources depending on thread priorities.
On Linux there's a specific command for this: sched_yield()
as from the man pages:
sched_yield()
causes the calling thread to relinquish the CPU. The thread is moved to the end of the queue for its static priority and a new thread gets to run.If the calling thread is the only thread in the highest priority list at that time, it will continue to run after a call to
sched_yield()
.
with also
Strategic calls to
sched_yield()
can improve performance by giving other threads or processes a chance to run when (heavily) contended resources (e.g., mutexes) have been released by the caller. Avoid callingsched_yield()
unnecessarily or inappropriately (e.g., when resources needed by other schedulable threads are still held by the caller), since doing so will result in unnecessary context switches, which will degrade system performance.