How do I guarantee that an object is dealloced on the main thread?
How do I guarantee that an object is dealloced on the main thread?
- Subject: How do I guarantee that an object is dealloced on the main thread?
- From: Brian Stern <email@hidden>
- Date: Sun, 5 Oct 2008 16:43:19 -0400
Hi All,
The thread "Re: premature dealloc of the datasource of a NSTableView
crashes my application" made me think about this problem again.
This is the question I really wanted to ask:
I have an object X that is alloc/inited on the main thread. This
object creates some NSThreads with
detachNewThreadSelector:toTarget:withObject, which have object X as
their target. At a later point I want to release object X and have it
be dealloced on the main thread.
How do I guarantee that object X is dealloced on the main thread?
The problem is this: the NSThread objects retain object X. I have a
stop method in object X that sets a 'cancelled' global that the thread
objects inspect and they then exit when it turns true. So I send stop
and then release on the main thread. The thread objects exit and
eventually release object X but the last release, which causes the
dealloc, can be on any thread.
I attempted to synchronize the exit of the thread objects' main method
using NSConditionLock. The synchronization worked but the dealloc
still occurred on a background thread because the release from the
NSThread happens after the main method returns.
I also tried to synchronize based on receipt of the
NSThreadWillExitNotification. The synchronization succeeded but this
also failed because the notification is also sent before the NSThread
releases its target.
I couldn't figure out any notification that is sent by the threads
that happens after the release of their target or after the die
entirely. I couldn't figure out what to wait for.
This question of stopping threads has been mentioned numerous times in
the archives but I didn't see this issue addressed.
Any thoughts?
--
Brian Stern
email@hidden
_______________________________________________
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