Sleep和WaitForSingleObject区别

231 阅读3分钟

一、Msdn种Sleep解读

This function suspends the execution of thecurrent thread for a specified interval.

终止线程指定的时间间隔。

void Sleep(

DWORD dwMilliseconds );

Parameters

dwMilliseconds

Specifies the time, in milliseconds, forwhich to suspend execution. A value of zero causes the thread to relinquish theremainder of its time slice to any other thread of equal priority that is readyto run. If there are no other threads of equal priority ready to run, thefunction returns immediately, and the thread continues execution. A value ofINFINITE causes an infinite delay.

Suspend执行指定的毫秒,0导致线程放弃它的剩余时间片转向执行其他同等优先级准备执行的线程。如果没有同等优先级的其他线程在运行,函数立即返回,并且当前线程继续执行。INFINIT导致其无限延时。

VOID Sleep(DWORDdwMilliseconds); 该函数可使线程暂停自己的运行,直到dwMilliseconds过去为止。

关于Sleep函数,有下面几个重要问题值得注意:

* 调用Sleep,可使线程自愿放弃它剩余的时间片。

* 系统将在大约的指定毫秒数内使线程不可调度。

* 你可以调用Sleep,并且为dwMilliseconds参数传递INFINITE。这将告诉系统永远不要调度该线程。这不是一件值得去做的事情。最好是让线程退出,并还原它的堆栈和内核对象。

* 你可以将0传递给Sleep。这将告诉系统,调用线程将释放剩余的时间片,并迫使系统调度另一个线程。但是,系统可以对刚刚调用Sleep的线程重新调度。如果不存在多个拥有相同优先级的可调度线程,就会出现这种情况。

二、Sleep和WaitForSingleObject区别

       Sleep的话,只是睡一段时间,时间一到,就变成可调度状态。而WaitForSingleObject则是等待某个内核对象变成有信号状态,其目的和意义很明显,因此更具有针对性。我个人的习惯,在主线程中不用WaitForSingleObject,因为它容易引起死锁。

WaitForSingleObjectSleep
等待信号返回,等待一定的时间
灵活;等待信号的时间内,信号也可能提前返回需要强制等待固定的时间

 

总结:如果在工作线程中有可能涉及到了消息驱动的API,那么不能在主线程中使用WaitForSingleObject一类函数,而必须使用上述的方案。[尚未遇到此类情况].

但[MSDN]上有详细介绍:

       Ifa thread creates any windows, it must process messages. Message broadcasts aresent to all windows in the system. A thread that uses a wait function with notime-out interval may cause the system to become deadlocked. Two examples ofcode that indirectly creates windows are DDE and COM CoInitialize.Therefore, if you have a thread that creates windows, use MsgWaitForMultipleObjectsor MsgWaitForMultipleObjectsEx,rather than WaitForSingleObject.

       如果线程创建了窗口,他必须处理消息。消息广播发送至系统中的所有窗口。一个使用没有时延间隔的等待函数可能导致系统死锁。在DDE和COM初始化的时候间接地创建了窗口。因此,如果通过线程创建了窗口,应该使用MsgWaitForMultipleObjectsor MsgWaitForMultipleObjectsEx,而不是WaitForSingleObject.。

借鉴了论坛里的一些回复,谢谢!