开发者

Difference between Thread.Sleep(0) and Thread.Yield()

As Java has had Sleep and Yield from long ago, I've found answers for that platform, but not for .Net

.Net 4 includes the new Thread.Yield() static method. Previously the common way to hand over the CPU to other process was Thread.Sleep(0).

Apart from Thread.Yield() returning a boolean,开发者_JAVA百科 are there other performance, OS internals differences?

For example, I'm not sure if Thread.Sleep(0) checks if other thread is ready to run before changing the current Thread to waiting state... if that's not the case, when no other threads are ready, Thread.Sleep(0) would seem rather worse that Thread.Yield().


As explained by Eric Lippert in his Coverity blog post “How does locking work in C#?” while demonstrating how to implement locking—

The .NET Framework gives you multiple tools you could use to build a more sophisticated waiting strategy: Thread.SpinWait puts the processor into a tight loop allowing you to wait a few nanoseconds or microseconds without ceding control to another thread. Thread.Sleep(0) cedes control to any ready thread of equal priority or keeps going on the current thread if there is none. Thread.Yield cedes control to any ready thread associated with the current processor. And as we’ve seen, Thread.Sleep(1) cedes control to any ready thread of the operating system’s choice. By carefully choosing a mix of these calls and doing performance testing in realistic conditions you could build a high-performance implementation, and of course this is what the CLR team has actually done.


According to the MSDN,

When using Sleep(0) The thread will not be scheduled for execution by the operating system for the amount of time specified.

With using Yield() The rest of the thread's current time slice is yielded. The operating system schedules the calling thread for another time slice, according to its priority and the status of other threads that are available to run.

So there's a minor difference in that. Thread.sleep will put a Thread into SLEEP mode with a recommendation that it stay there for the given number of milliseconds Thread.yield will put it into WAIT mode so it may run again straight away, or a higher process thread might step in.


Thread.Sleep(0) relinquishes the thread’s current time slice immediately, voluntarily handing over the CPU to other threads.

Framework 4.0’s new Thread.Yield() method does the same thing — except that it relinquishes only to threads running on the same processor.

source

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜