Significance of Sleep(0)

前端 未结 8 2093
醉酒成梦
醉酒成梦 2020-12-03 02:19

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

8条回答
  •  無奈伤痛
    2020-12-03 02:58

    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 calling sched_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.

提交回复
热议问题