对线程控制 中 Sleep(0),和 Sleep(1)的 //对相关转帖的理解

来源:互联网 发布:九阴真经最新辅助软件 编辑:程序博客网 时间:2024/04/29 01:18

说明:

     笔者在 网上看到的对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);

    }

   }