Re: Mutex/Lock
On May 31, 10:39 am, Chris Forone <4...@gmx.at> wrote:
Errata:
bool Exit()
{
mutex.Acquire();
if (active)
{
active = false;
mutex.Release();
// wait for thread termination :-)))
}
mutex.Release();
}
if i write:
active = false, mutex.Release()
i think, the mutex is first released -> error
is this right?
No. There's a sequence point at the comma, so all side effects
of the preceding expression must be finished before any side
effects of the following occur.
I do wonder about your code, however. You really need to
recover the mutex before the end of the if---otherwise, you'll
release it twice. And how do you wait for thread termination:
with a join, or with some sort of global thread counter? In the
latter case, you'll need the mutex to read it as well.
I generally use something like:
void
requestTermination()
{
ScopedLock lock( terminateFlagMutex ) ;
terminateRequested = true ;
}
void
waitForAllThreadsToTerminate()
{
ScopedLock lock( threadCountMutex ) ;
while ( threadCount != 0 ) {
threadCountCondition.wait( lock ) ;
}
}
void
terminate()
{
requestTermination() ;
waitForAllThreadsToTerminate() ;
}
with:
void
endOfThread()
{
ScopedLock lock( threadCountMutex ) ;
-- threadCount ;
threadCountCondition.notify() ;
}
at the end of each thread. (Note that this does require some
care when starting threads, since a race condition can occur
there if you're not careful. In my case, it's not a problem,
because all of the threads are always started by the main
thread, which is also the only thread which will call
terminate(), but if other running threads might start a thread
while you're calling terminate, you'll have to add some
additional logic in thread start-up to avoid the race.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34