0

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()

4

1 回答 1

0

我刚刚注意到的一件事:你为什么要设置m_ReceiverEnabledtrue?它应该设置为false。我在下面的代码中做到了这一点。

即使您确定竞态条件不是问题的根源,由于使用了自动重置事件,您仍然会遇到竞态条件。你能解决它,然后看看这是否也能解决你的主要问题?这是使用手动重置事件而不是无竞争方式的代码:

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;
}
于 2013-10-17T15:52:15.923 回答