RE: [GD-Windows] Stopping a thread cleanly
Brought to you by:
vexxed72
|
From: Brian H. <bri...@py...> - 2002-02-17 20:09:22
|
> Which specific kind of synchronization are you doing here?
This is real primitive stuff. Basically it's a background thread that's
filling a soundbuffer for streaming audio. Works great, except for the
potential race condition that occurs when I need to shut down the
thread/streaming audio. To kill the thread I was using a global
variable, which was a bit messy, but I've now switched to
WaitForSingleObject which is a lot cleaner.
I'm using both a critical section and the event -- the critical section
guards against access to the actual streaming buffer and DSound data,
the event is just to signal to the thread to quit.
Off the top of my head, my new loop is something like:
while ( 1 )
{
//Guard access to the shared data used in DoWork()
EnterCriticalSection();
//Make sure that the event wasn't signaled prior to
//entering the critical section
if ( WaitForSingleObject( ... ) == WAIT_TIMEOUT )
{
DoWork();
LeaveCriticalSection();
}
else
{
LeaveCriticalSection();
break;
}
//Sleep for 250ms or until the event is signaled
//indicating that the thread should die
if ( WaitForSingleObject( event, 250 ) == WAIT_OBJECT_0 )
{
break;
}
//Theoretically a thread switch could occur between here
//and entering the critical section, which is why
//we check again inside the critical section for the
//event
}
Brian
|