Threads and retain/release
Threads and retain/release
- Subject: Threads and retain/release
- From: Dave DeLong <email@hidden>
- Date: Tue, 26 May 2009 08:41:17 -0600
Hey everyone,
I'm working on an app that needs to work on 10.4 and is multi-threaded. One of the nice things about 10.5 is the ability to create NSThread objects in ways other than [NSThread detachNewThreadSelector...]; Since that option isn't available to me, here's what I've decided to do:
I've created an NSObject subclass called "DDThread". DDThread has a start and cancel method (just like NSThread), and a BOOL ivar to indicated the thread's cancelled state. Messaging DDThread to -start will (internally) call the [NSThread detachNewThreadSelector...] method. This runs one of DDThread's private methods, which loops as long as the DDThread isn't cancelled.
All of this works fine. My question has to do with memory management and thread cleanup.
The docs indicate that when one detaches a new thread selector, an NSAutoreleasePool should be created. My question is: is it safe to call [self release] after the pool is destroyed? Here's why I think I need to do this: In another object, I store DDThreads in an NSMutableArray, so that I can find them if I need to cancel one. I retrieve it from the array, tell it to -cancel, and remove it from the array. However, if the DDThread is in the middle of its processing loop, it won't know that it has cancelled until it comes around on the next circuit, at which point it exits the loop, cleans up some stuff, and terminates the thread (by exiting the method).
By removing it from the array, the DDThread technically should be immediately deallocated (since nothing else retains it). Since there's another thread involved (the DDThread's busy loop), I can't have it be destroyed (the loop MUST clean up some stuff), hence my desire for the DDThread to retain itself until the busy loop has time to do its thing.
So again, is it safe for me to call [self release]; outside the scope of the NSAutoreleasePool? AFAICT, I can't [self release] before releasing the pool, since that would destroy the object, rendering the remainder of the method (like releasing the pool) somewhat invalid (please correct me if I'm wrong).
Thanks!
Dave DeLong
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden