對線程控制 中 Sleep(0),和 Sleep(1)


【原文地址】http://blog.csdn.net/qinwei/article/details/5728393

說明:

     筆者在 網上看到的對Sleep(0)的理解如下:

 

/*

    本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/burningcpu/archive/2008/09/20/2955275.aspx

     Sleep(n)的作用是讓當前線程睡眠n毫秒,以便執行其他線程,如果沒有其他線程,那睡眠n毫秒後,繼續執行。
    而如果n=0,Sleep(0)是指CPU交出當前線程的執行權,讓CPU去執行其他線程。也就是放棄當前線程的時間片,轉而執行其他線程。

    那麼,Sleep(0)應該在那種情況下使用? 一般來說,如果當前線程比較耗時比較佔CPU資源,可以在結尾處加上Sleep(0), 這樣效率會得到大大的提高。

    另外,還可以用這種方法來保證線程同步,線城池工作時,主線程使用Sleep(0)來等待線程池裏所有的線程都完成運行。當線程池線程非常多的時候,這種方法確實是一種非常有效的節省cpu的方式,因爲它節省了在線程裏使用內核來進行同步的開銷。

*/

 

/*

轉載MSDN:

Sleep

The Sleep function suspends the execution of the current thread for a specified interval.

VOID Sleep(   DWORD dwMilliseconds   // sleep time in milliseconds );  

Parameters

dwMilliseconds
Specifies the time, in milliseconds, for which to suspend execution. 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. A value of INFINITE causes an infinite delay.

Return Values

This function does not return a value.

Remarks

A thread can relinquish the remainder of its time slice by calling this function with a sleep time of zero milliseconds.

 

*/

 

筆者理解以及實際使用:

 

  【1】Sleep(0)正如 參數所示,在遠小於1 ms 的時間片內允許其他線程調度CPU 的運行,而保留了絕大部分CPU時間片爲本線程運   行

  【2】換句話說就是Sleep(0)幾乎掌控了所有CPU的使用權,而非讓出CPU使用權。

 

  【2】相反:Sleep(1)在參數非0 下,休眠1 ms並且極大的讓出CPU使用權, 但可能正由於讓出CPU使用權,使得本Sleep休眠控制的很不精準,可能相差幾十 毫秒以上

  【3】實例如下:

   UINT thread_func(LPVOID lp)
   {
    while(TRUE)
    {

       Sleep(0);

    }

   }

 

   UINT thread_func(LPVOID lp)
   {
    while(TRUE)
    {

       Sleep(1);

    }

   }
 

發佈了102 篇原創文章 · 獲贊 2 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章