Re: Question about Threading
Re: Question about Threading
- Subject: Re: Question about Threading
- From: Chris Kane <email@hidden>
- Date: Wed, 10 Aug 2005 13:52:35 -0700
On Aug 10, 2005, at 12:07 PM, James Bucanek wrote:
Chris Kane wrote on Wednesday, August 10, 2005:
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.
Whoa, Chris. You're completely freaking me out! If I understand
what you wrote correctly, you're saying that if thread A gets a
lock on an NSLock, then thread B shouldn't release it? I've been
doing exactly this for donkey's years:
- Create and lock some result object
- Start a new thread with the calculation of that object
- New thread starts and will release the lock on the result
object when done
- Go do other stuff
- When I want the results, I request a second lock on the
result object.
- When I obtain the lock, I read the results.
If by "request a second lock on the result object" you mean "attempt
to lock the lock", and aren't making a different lock object, then
yes, this pattern is wrong. You should be using conditions, and
blocking by use of a wait routine, and signalling the finished state
via a signal/broadcast routine of some sort. Mutex locks by
themselves are not appropriate for rendezvous of multiple threads.
NSConditionLock in the Cocoa API can be used for this, which hides
the waiting and the signalling, though it's not the most convenient
class since you need to reduce your conditions to simple distinct
integer values.
In your case, that isn't difficult, since you just need two "thread
working" and "thread done" states. You would initialize the new
condition lock with the "thread working" state and start the
background thread. When it's done, the background thread would lock
the condition lock then immediately unlock it with the "thread done"
condition. The other thread, when it needs to block waiting for the
thread to finish should "lock when condition 'thread done'".
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