# Working with threads

Most of Cocoa, and thus PyObjC, requires an NSAutoreleasePool in order to function properly. PyObjC handles this automatically on the first thread it is imported from, but other threads will require explicit NSAutoreleasePool management. The following practice for working with NSAutoreleasePool is recommended:

pool = NSAutoreleasePool.alloc().init()
...
del pool


Typically this will be done at the beginning and end of the thread. It is important to use del before rebinding the pool local variable to another NSAutoreleasePool instance, otherwise it will not have the intended effect.

For long running threads and tight loops, it can also be useful to use this pattern in the body of the loop in order to optimize memory usage. For example, NSRunLoop will be create a new NSAutoreleasePool at the beginning of each run loop iteration and release it at the end.