Re: [SOLVED] Delayed -dealloc occurs on worker thread if object is "working".
Re: [SOLVED] Delayed -dealloc occurs on worker thread if object is "working".
- Subject: Re: [SOLVED] Delayed -dealloc occurs on worker thread if object is "working".
- From: Michael Ash <email@hidden>
- Date: Fri, 4 Jun 2010 12:20:03 -0400
On Fri, Jun 4, 2010 at 11:27 AM, Jerry Krinock <email@hidden> wrote:
>
> On 2010 Jun 02, at 10:48, BJ Homer wrote:
>
>> detachNewThreadSelector:target:withObject: retains both the target and the object.
>
> Thank you, BJ. That explains everything.
>
> On 2010 Jun 02, at 11:12, Jens Alfke wrote:
>
>> It’s really not a good idea to obsess over the details of when objects get dealloced, unless of course you’re running into dealloced-object crashes or memory leaks.
>
> Actually Jens, I was looking for a memory leak, but now I see that this was caused by a "thread leak". I had wrapped a kqueue in a target object which runs an infinite loop camping on kevent() in a secondary thread. Forever. The fix is, when done with the kqueue, I now close() its file descriptor, which I should do anyhow. Conveniently, this causes kevent() to return an error, running the loop one last time, because when I detect the error I break out of the loop. Then the thread ends and, as BJ says, releases the thread's target and object.
This is a bad approach, because it has a race condition. Consider the
following sequence of events:
Kqueue thread: receives an event, processes it.
Closer thread: closes the file descriptor.
Random other thread: opens a new kqueue (this could happen in a thread
you have no control over, e.g. in Cocoa, so it's no help if you don't
do this yourself) and by coincidence receives the same file descriptor
that you just closed.
Kqueue thread: finishes processing the event, calls kevent() on the
closed-and-now-reopened file descriptor. Hilarity ensues.
The correct approach here is to create a pipe using the pipe() call
and listen for the read end of the pipe on your kqueue. When you want
to shut down the kqueue, write to the pipe. That will unblock your
call to kevent(), and the fact that the pipe has data can be used as
the signal to end the thread.
Mike
_______________________________________________
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