Follow-up questions on sample class ThreadSafeQueue
Shawn Erickson
shawnce at gmail.com
Tue May 15 16:37:41 PDT 2007
On 5/15/07, Duncan Champney <duncanc at aol.com> wrote:
> Chris,
>
> Thanks for the link to the ThreadSafeQueue post. It makes good sense
> to me to use NSConditionLock to manage shared access to a job queue.
>
> I have a couple of follow-up questions.
>
> I'm a little unclear on how the worker threads would use the
> ThreadSafeQueue. I would think the ThreadSafeQueue object's methods
> would run on the main thread, and the worker threads would call those
> methods using performSelectorOnMainThread.
Why do you think that? The whole point of the class is to allow
multiple threads to utilize the same queue directly. That is why it
uses NSConditionLock to protect the data structure it manages.
> Also, I'm puzzled by a couple of lines in the method implementation.
> Why do the methods in -dequeue and -tryDequeue retain and autorelease
> the object from "elements" in the same call. Here's the line from
> tryDequeue:
>
> element = [[[elements objectAtIndex:0] retain] autorelease];
That retains the objects and balances that retain with an autorelease.
That ensures that the object will continue to exist at least until
sometime in the future when the current autorelease pool is released
(drained).
Why is this done? Well the removeObjectAtIndex: message could result
in the "element" object being deallocated because the elements array
could be the last object holding a retain on "element".
> The retain and autorelease calls would seem to cancel each other out.
That is true but not immediately.
> The retain call would increase the retain count for the object in
> "elements", and then the autorelease would immediately decrement it,
> for a net null effect.
No autorelease doesn't immediately decrement the retain count. Review
the concept of NSAutoreleasePools.
-Shawn
More information about the MacOSX-dev
mailing list