Windows setevent processing

I wonder how setevent is handled internally within Windows.

I have the following situation

Std::thread thread loop which executes while std::atomic == true Inside the loop is a waitforsingleObject which sleeps infinite in alertable state.

A function stopThread() which does the following: - Clears the atomic bool - Calls Setevent on the event object - Calls thread.join

This often hangs, I get the impression that setevent has still some work to do in the current thread, while join blocks the current thread.

If I add an additional Boolean in the thread which is set after waitforsinlgleObject and I wait for this to be set before calling join() Everything seems to work ok.

Code (error checking omitted here)

Init code/declarations:

 HANDLE m_WakeupThreadEvent;
 std::atomic<bool> m_ReceiverEnabled;
 m_WakeupThreadEvent = CreateEvent(NULL, false, false, "RxThreadWakeupEvent" );

Thread code:

while(m_ReceiverEnabled)
{
    DWORD rslt = WaitForSingleObjectEx(m_WakeupThreadEvent, INFINITE, true);
    // Here some checking for rslt;
}

function code:

m_ReceiverEnabled = true;
SetEvent( m_WakeupThreadEvent )
m_Thread.join()

Is there some explanation for this behavior ? I could not find any details about the operation of setEvent()


One thing I just noticed: Why are you setting m_ReceiverEnabled to true ? It should be set to false . I have done this in the code below.

Even if you're certain a race condition is not the root of your problem, you still have a race condition due to using an auto-reset event. Can you fix it, then see if that also happens to take care of your main problem as well? Here is code which uses a manual reset event instead in a race-free manner:

HANDLE m_WakeupThreadEvent;
std::atomic<bool> m_ReceiverEnabled;
m_WakeupThreadEvent = CreateEvent(NULL, TRUE, FALSE, "RxThreadWakeupEvent" );

m_ReceiverEnabled = false;
SetEvent( m_WakeupThreadEvent )
m_Thread.join()

while(true)
{
    DWORD rslt = WaitForSingleObjectEx(m_WakeupThreadEvent, INFINITE, true);
    ResetEvent(m_WakeupThreadEvent);
    if(!m_ReceiverEnabled)
        break;
    // Here some checking for rslt;
}
链接地址: http://www.djcxy.com/p/5206.html

上一篇: 当指定launch :: async时,std :: async不会执行

下一篇: Windows setevent处理