Re: Question about Threading
Re: Question about Threading
- Subject: Re: Question about Threading
- From: Chris Kane <email@hidden>
- Date: Wed, 10 Aug 2005 08:55:16 -0700
On Aug 8, 2005, at 7:14 AM, Cameron Hayne wrote:
On 8-Aug-05, at 8:39 AM, Michael Becker wrote:
I have created a (class-wide) boolean variable which the thread
checks on each iteration to see whether it may continue or not.
However, I get synchronizing problems: When I set that boolean
variable to STOP the thread, how can I make sure that I wait until
the thread has finished its current iteration and then exited?
What (in general) is the best way of doing things like that?
You want to use NSLock.
You might find it useful to look at my example project "ImageCalc"
that illustrates use of NSLock:
http://hayne.net/MacDev/ImageCalc/
I'm not saying the above example does this, just providing the
following warning...
Don't, however, try to solve the synchronization and "wait until the
background thread is done" by locking a lock in one thread which the
other thread unlocks. That invokes undefined behavior in the
underlying POSIX lock objects, and is a bad idea. I warn about this
because it is tempting to do because it seems simple. One should
never use mutex locks to implement "conditional waiting" is the
point; that is, never use -lock on a mutex in a "block until
something happens" sense, where the event is signalled by some other
thread (obviously, since the current thread is now blocked on the
lock) unlocking the previously locked lock.
NSConditionLock *could* also be used, and could take the place of
your boolean variable and a lock by defining two condition states
(0/1) which represent the SHOULD_KEEP_RUNNING and SHOULD_STOP states
of the boolean, and a third state HAS_FINISHED which the background
thread can move the condition lock into when it sees the SHOULD_STOP
state and decides to exit (just before exiting). You would then use
combinations of unconditional and conditional [try-]locking and
unlocking to read and set the state in the various threads. On the
whole I don't know if that is an improvement, but if you want
conditional but absolute (no events handled) blocking after setting
SHOULD_STOP until the background thread sees that and moves to the
HAS_FINISHED state, then NSConditionLock would be reasonable.
Chris Kane
Cocoa Frameworks, Apple
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden