Search This Blog

Friday, June 10, 2005

Events - New Windows Implementation

This one's almost identical to the last. All I did was remove the timed Wait and replace with a TryWait, for compatability with the new POSIX verion.

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, otherwise false
inline bool TryWait()
{
DWORD nRetVal = WaitForSingleObject(m_hEvent, 0);
assert(nRetVal != WAIT_FAILED);

if (nRetVal == WAIT_TIMEOUT)
return false;

return true;
}

// Waits indefinitely for the event to be set
inline void Wait()
{
verify(WaitForSingleObject(m_hEvent, INFINITE) != WAIT_FAILED);
}
};

1 comment:

Anonymous said...

holy moly ...this blog rocks