Just a few small questions today that I came up with when working on a
multithreaded worker / overseer implementation =)
I have a situation where in a windows environment one thread first rises a
flag indicating a second thread should terminate. Then, the first thread calls
Resume() on the second thread - just in case it might be suspended - and
then calls WaitForSingleObject(secondthread). The second thread runs in a
loop, and is testing for the exit flag in each cycle.
i.e. in pseudocode
// The second thread's main loop
void ThreadLoop
{
while (true)
{
// Lock all data used by this thread
SetMutex();
// See if we should terminate.
// If so, fall out of the thread loop
if (bExitFlag)
{
ReleaseMutex();
return;
}
// Otherwise, do our working stuff, and then
// release the mutex again.
DoSomeStuff();
ReleaseMutex();
// Finally, start sleeping so we won't cost any cycles
Suspend();
}
}
// The first thread's function to terminate the second thread
void TerminateOtherThread()
{
// Set the exit flag for the other thread
SetMutex();
bExitFlag = true;
FreeMutex();
// Now, revive the other thread in case it is suspended,
// and then, wait for its termination
ResumeThread(secondthread);
WaitForSingleObject(secondthread);
// Release remaining thread API stuff
CloseHandle(secondthread);
}
So now, on to the questions that popped into my mind.
May this setup lead to a deadlock ? - I think so.
Why ? Because ResumeThread() may be called before the second thread is
actually suspended, thus doing nothing, then the second thread Suspends(),
and finally the first thread waits for a suspended second thread, so thats a
no-no. Any workaround solution - except perhaps putting a mutex around the
suspending command ?
Second, is WaitForSingleObject terminating when the specified process _is_
terminated, or when it has _been_ terminated ? The MSDN is a little unclear
about this. So if my second thread ends before my first thread actually
reached the WaitForSingleObject() call, will WaitForSingleObject return as it
should?
The entire setup represents a rendering thread within a larger physics
simulation. Is suspending the rendering thread even a good idea
performancewise if we are aiming at 30 frames or so per second ?
And finally, do I need to set a mutex if I just change a single boolean
variable ? I guess I needn't, since the variable set operation should be
atomar anyways.
I'm not too experienced in this whole multithreaded business, so I'd be glad
about any input. =)
Thank you for you help and time,
Cheers,
- Wernaeh












