Re: waiting for another thread without blocking resources...
On Feb 14, 10:59 am, Lars Uffmann <a...@nurfuerspam.de> wrote:
In an event routine, I want to end a certain thread. I am
setting a flag that is checked by the thread and causes it to
end, when it is set. Then the thread sets a "response" flag,
just before exiting. In the event routine, I would like to
wait for that response flag, because at that point, I can be
sure that the old thread (even if it still is alive between
setting the response flag and exiting) will no longer
interfere with a subsequent call.
However, a
while (!responseflag);
heavily blocks system resources and apparently also the read
call blocks the writing of the responseflag - I get caught in
an endless loop there.
while (!responseflag) cout << "." << endl;
seems to do the job, with a random amount of periods printed
to stdout, but I wouldn't rely on it always working. So what
is the thing to do within that while loop?
Not only does it use an ungodly amount of CPU time to do
nothing, it isn't guaranteed to work. You need some sort of
synchronization around the accesses to responseflag, since it is
being modified, and more than one thread is accessing it.
The standard solution here is to use a condition. Something
like:
bool responseflag ;
boost::mutex responseMutex ;
boost::condition responseCond ;
void
waitForResponse()
{
boost::mutex::scoped_lock l( &responseMutex ) ;
while ( ! responseflag ) {
responseCond.wait( l ) ;
}
}
And of course, to modify the flag, you'll need:
void
setResponse( bool newValue )
{
boost::mutex::scoped_lock l( &responseMutex ) ;
responseflag = newValue ;
responseCond.notify_all() ;
}
(And of course, this just calls to be put in a simple
synchronization class.)
However: if all you want to do is wait for the end of the
thread, what's wrong with join?
--
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