Thread.Sleep(0)和Thread.Yield()之间的区别 [英] Difference between Thread.Sleep(0) and Thread.Yield()

查看:191
本文介绍了Thread.Sleep(0)和Thread.Yield()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Java在很久以前就具有Sleep和Yield功能,因此我发现

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

.Net 4包括新的Thread.Yield()静态方法.以前,将CPU移交给其他进程的常用方法是Thread.Sleep(0).

除了返回布尔值的Thread.Yield()之外,还有其他性能,操作系统内部差异吗?

例如,我不确定Thread.Sleep(0)在将当前线程更改为等待状态之前是否检查其他线程是否已准备好运行...如果不是这样,当没有其他线程准备就绪时,Thread.Sleep (0)似乎比Thread.Yield()还要糟糕.

.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, 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().

推荐答案

正如Eric Lippert在Coverity Blog上的解释,同时演示了如何实现锁定- 来源

As explained by Eric Lippert at the coverity blog while demonstrating how to implement locking - source

.NET Framework为您提供了多种工具,可用于构建更复杂的等待策略:Thread.SpinWait将处理器置于紧密的循环中,允许您等待几纳秒或几微秒的时间,而无需将控制权移交给另一个线程. Thread.Sleep(0)将控制权移交给具有相同优先级的任何就绪线程,如果没有线程,则继续运行当前线程. Thread.Yield将控制权移交给与当前处理器关联的任何就绪线程.如我们所见,Thread.Sleep(1)将控制权移交给操作系统选择的任何就绪线程.通过仔细选择这些调用的组合并在实际条件下进行性能测试,您可以构建高性能的实现,而这当然是CLR团队实际上所做的.

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.

这篇关于Thread.Sleep(0)和Thread.Yield()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆