關於線程同步 PulseEvent()

來源:互聯網
上載者:User

最近一直在看《windwos核心編程》,關於線程同步,有這樣一個函數PulseEvent().

在MSDN上解釋如下:

 

      This function provides a single operation that sets to signaled the state of the specified event object and then resets it to nonsignaled after releasing the appropriate number of waiting threads.

      (這個函數設定特定的事件對象為有訊號狀態,然後釋放相關的等待線程,再置時間對象為無訊號狀態)

但是MSDN又說了,這個函數是不好的,最好不要使用。

 

       對於Event對象,我們知道,分手動重設和自動重設兩種。手動重設Event,需要認為控制訊號的有無,可以有多個線程等待同一個Event對象,當變成有訊號狀態時,等待的各個線程都可以被啟用。那麼對於自動重設事件,啟用其中一個線程之後會自動變成無訊號狀態,幾個競爭的線程只能有一個獲得啟用。

 

      然而,在使用PulseEvent()的時候卻發現,等待的線程並不能都被啟用,那麼,究竟發生了什麼呢?

看下面的代碼,你是否以為會如你所願的進行?

 

 

     SignalSemaphore(hOtherSemaphore);
     WaitForSingleObject(hEvent, INFINITE);

 

事實上,這並不總是正確的。因為在訊號和等待之間存在競爭,如果在一個線程PluseEvent()的時候,恰好沒有線程處於等待狀態,那麼這個事件將丟失!

這是我在網上搜到的一段話:

     While the thread is sitting waiting for the event, a device driver or part of the kernel itself might ask to borrow the thread to do some processing (by means of a "kernel-mode APC"). During that time, the thread is not in the wait state. (It's being used by the device driver.) If the PulseEvent happens while the thread is being "borrowed", then it will not be woken from the wait, because the PulseEvent function wakes only threads that were waiting at the time the PulseEvent occurs.

很好的解釋了這種現象的原因,原來一個線程處於等待狀態的過程中,會有一些瞬間其狀態並不為“等待狀態”。這就造成PulseEvent()不能啟用應該被啟用的等待線程。

 

     這些瞬間包括什麼呢?比如發生了系統調用,缺頁中斷,硬體中斷......等等。

 

     怎麼解決這個問題呢?MSDN建議使用SiginalObjectAndWait()。具體資訊可以查詢MSDN.

     終於知道為什麼PulseEvent()是不可靠的了:)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.