Re: MT Design Question
On Aug 29, 10:02 am, "Chris M. Thomasson" <cris...@charter.net> wrote:
"Joshua Maurice" <joshuamaur...@gmail.com> wrote in message
Do you have any nontrivial
examples where windows event classes result in simpler and more
efficient code than the condition variable alternative?
An event can make some code simpler. Take a slow path for, say a simple
mutex algorithm:
<event version - pseudo-code sketch>
_________________________________________________________
struct mutex
{
LONG m_state; // = 0
HANDLE m_waitset; // auto reset event; set to false
void lock()
{
if (InterlockedExchange(&m_state, 1))
{
while (InterlockedExchange(&m_state, 2))
{
WaitForSingleObject(m_waitset, INFINITE);
}
}
}
void unlock()
{
if (InterlockedExchange(&m_state, 0) == 2)
{
SetEvent(m_waitset);
}
}};
Ok. Still in a rush, but I'm just noting that I'm unclear as to
whether it's correct now (ignoring spurious wakeups and timed waits. I
think that those make it incorrect.)
Let me try this scenario:
Thread 1 comes in lock(), exchanges it to 1, sees previous 0
Thread 2 comes in lock(), exchanges it to 1, sees previous 1
Thread 1 exits lock(), and runs through unlock(). He does not see it
as 2, so he does not set the event.
Thread 2 comes along to the while loop, and waits indefinitely as no
one else set the event.
I think this example holds, meaning that this lock is pretty broken.