Search This Blog

Friday, May 27, 2005

Events - Windows Version

As with semaphores, Windows supports events directly. In fact, the interface for using events is very similar to using semaphores; you create them with CreateEvent, close them with CloseHandle, wait on them with WaitForSingleObject, set them with SetEvent, and reset them with ResetEvent. Intuitive, no?

The code, which does not particularly need any further explanation:


class CEvent // Win32 version of CEvent (slow)
{
private:
HANDLE m_hEvent;

inline HANDLE GetEvent()
{
return m_hEvent;
}

public:
// bAutoReset controls how the event reacts when it gets set. An auto-reset event will automatically go back to the unset state after one thread gets released from waiting because of the event being set. A non-auto-reset event will stay set until reset explicitely. CEvent throws bad_alloc if it cannot create the event.
inline CEvent(bool bAutoReset, bool bSet)
{
m_hEvent = CreateEvent(NULL, !bAutoReset, bSet, NULL);
if (!m_hEvent)
throw std::bad_alloc("Unable to create event");
}

inline ~CEvent()
{
verify(CloseHandle(m_hEvent));
}

inline void Set()
{
verify(SetEvent(m_hEvent));
}

inline void Reset()
{
verify(ResetEvent(m_hEvent));
}

// Returns true if the event was set, false if the timeout expired
inline bool Wait(unsigned int nTimeoutMS)
{
DWORD nRetVal = WaitForSingleObject(m_hEvent, nTimeoutMS);
assert(nRetVal != WAIT_FAILED);

if (nRetVal == WAIT_TIMEOUT)
return false;

return true;
}

// Waits indefinitely for the event to be set
inline void Wait()
{
verify(Wait(INFINITE));
}
};

No comments: