On Fri, Jun 4, 2010 at 11:27 AM, Jerry Krinock <je...@ieee.org> 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 (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to