1、问题
在线程中我们会经常按如下写代码,Sleep(0)比Sleep(1)更容易获得时间片
DWORD WINAPI SampleThread(PVOID pvParam)
{
while ( true )
{
// do something
Sleep(1);
}
return 0x50;
}
2、原因
MSDN说明如下:
Remarks
This function causes a thread to relinquish the remainder of its time slice and become unrunnable for at least the specified number of milliseconds, after which the thread is ready to run. In particular, if you specify zero milliseconds, the thread will relinquish the remainder of its time slice but remain ready. Note that a ready thread is not guaranteed to run immediately. Consequently, the thread may not run until some time after the specified interval elapses. For more information, see Scheduling Priorities.
Sleep(1)导致线程释放剩余的时间片,并停止运行至少1毫秒,然后恢复为就绪状态。
Sleep(0)导致线程释放剩余的时间片,并立即进入就绪状态。
所以如果有两个同等优先级的线程一个使用Sleep(1),一个使用Sleep(0),后者将更多的抢到时间片。