一、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,因為它容易引起死結。
WaitForSingleObject |
Sleep |
等待訊號返回, |
等待一定的時間 |
靈活;等待訊號的時間內,訊號也可能提前返回 |
需要強制等待固定的時間 |
總結:如果在背景工作執行緒中有可能涉及到了訊息驅動的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.。
借鑒了論壇裡的一些回複,謝謝!