windows线程yield以及Sleep(0)和SwitchToThread之间的区别

C++的自定义线程函数内调用了一个自定义的yield()接口。

在windows上是调用了SwitchToThread来实现的,linux是pthread_yield实现的。

Sleep(0):时间片只能让给优先级相同或更高的线程; 
SwitchToThread():只要有可调度线程,即便优先级较低,也会让其调度。

下面是MSDN上对Sleep函数的描述:

The time interval for which execution is to be suspended, in milliseconds.

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.

Windows XP/2000:  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.

可以看到,从2003 server开始,Sleep(0)变成了调度所有可调度线程,跟SwitchToThread差不多了。

原文地址:https://www.cnblogs.com/kex1n/p/5142752.html