当cpu占有率过高时-sleep(0)的妙用

After the sleep interval has passed, the thread is ready to run. If you specify 0 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 sleep interval elapses. For more information, see Scheduling Priorities.

仔细读下MSDN上这一段。简单地说,当Sleep(0)的时候,线程会放弃当前时间片,但是仍然保持可运行状态,直到下次有空闲时间片就会被重新运行,相当于放弃时间片后被放到了所有可运行线程的队列尾部。Sleep(0)的用途是,你仅仅想简单放弃时间片,给别的线程一个运行机会,而且希望系统有空闲的时候自己能尽快被再次调度。纯粹运算的线程可以通过Sleep(0)放出一些时间片,给其他IO线程一个喘息的机会。频繁调用Sleep(0)会让性能大幅下降,请谨慎使用。在程序不大的时候而且cpu占有率很高的情况下,某种条件下,在while(ture)最后的位置可以放上sleep(0),可以起到降低cpu占比的作用。当然并不建议程序有死循环,而且sleep(0)这种办法并不是最好的办法,还是需要重新设计代码结构来避免cpu占有率过高的问题。

原文地址:https://www.cnblogs.com/still-smile/p/13362768.html