Skip navigation.
 
mlRe: NSConnection/NSSocketPort per-subthread Mach port leak. Not just for NSSocketPort anymore...
FROM : Kirk Kerekes
DATE : Tue Jul 18 03:01:54 2006

RE: <rdar://problem/4621753>

I have now confirmed that this port-leak occurs also with Mach (+
[NSPort port]) ports used for DO between local threads. <rdar://
problem/4621753> has been updated appropriately, including a new 
version of the leak-demo application project.

To summarize:

If you create a NSConnection in the main thread, call 
enableMultipleThreads: on it and pass it to an ad-hoc* sub-thread for 
use in main-thread-to-sub-thread communication, each _sub-thread_ 
that _uses_ that NSConnection will leak 3 Mach ports** -- a leak that 
is essentially invisible with the standard testing tools 
(MallocDebug, et al), but which you can see with "top" or Activity 
Viewer (#Ports column). These Mach ports do _not_ go away when the 
thread terminates, but only when your application terminates.

If a thread doesn't actually use the NSConnection, no leak. But the 
leak is per thread, not per use of the NSConnection in the thread. A 
thread can use the NSConnection 100 times, but still will just leak 
the 3 ports. But 100 thread-instances using a shared NSConnection 
once apiece leak 300 ports.

If instead you create your sub-thread NSConnection _in_ each of the 
ad-hoc sub-threads (and do not need to call enableMultipleThreads: on 
it), no leak.

If instead you create a single "permanent" sub-thread, rather than 
create ad-hoc threads as needed, no leak that matters. (You are 
probably leaking a few ports, but only once).

Any use of enableMultipleThreads: with multiple ad-hoc sub-threads 
should be examined carefully. Because a Mach port leak consumes 
"wired" memory it eventually affects the entire system, not just an 
individual application.

Anyone writing something approximating a "server" should be 
particularly aware of this issue -- it is easy to miss in typical 
short-duration testing, but in long-duration use the result of a Mach 
port leak is that eventually the entire Mac will shudder to a halt. 
With most Macs not being restarted between System Software updates, 
it is quite possible for _any_ app to cause a problem with a port 
leak. Many users never knowingly Quit an app -- most "normal users" I 
know usually have 12-20 apps running simultaneously, many of which 
they haven't looked at in weeks.

If anyone happens to know some voodoo that will release these ports, 
I'm all ears. I have a nice test-bed app to test the voodoo in. If 
you want a copy of the test-bed app, send me an email.

-- FOOTNOTES --------------------------------------------------

* By "ad-hoc sub-thread" I am referring to a thread that is spawned 
when needed, and which exits when it has completed its task.

** More precisely, the first sub-thread _appears_ to leak 2 ports, 
and each subsequent thread leaks 3.

Related mailsAuthorDate
No related mails found.