當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占有率過高的問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM