Does every thread need its own autorelease pool?
Asked Answered
S

3

4

Does every thread have to have its own pool? I am writing an iPhone app which uses threads. If I do not put a pool on a thread it complains abut leaking.

What I wanted to do was to store some object which outlives the thread. How can I do it?

Strobila answered 28/12, 2010 at 16:45 Comment(0)
R
7

No, every NSThread has its own NSRunLoop, but not its own NSAutoreleasePool. Thus you have to create one and if you are performing a large operation or a operation that needs a lot of time, you really should drain the pool from time to time to keep your memory footprint low.

Object storage isn't bound to a thread at all, you can access every object from every thread you want, but it is possible that the accessor to the object isn't threadsafe and thus kills your app. However, this depends on your app and your code and not on threads.

Rubescent answered 28/12, 2010 at 16:49 Comment(3)
So how can I safely release the NSAutorelease pool? If I remove it there are complaints of leaks.Strobila
Remove it only at the end of your threads lifecycle, in the meantime you have to recreate it when you need to remove it for whatsoever reason.Rubescent
@John - You shouldn't remove the autorelease pool. Create it within the thread so that it can manage autoreleased objects, but anything you wish to hang around after the thread has finished executing should be manually retained (and later manually released), or initialized using -init or copy.Tenenbaum
X
3

To precise a little bit what JustSid said : When autorelease is called on an object, the autoreleasepool associated with the current thread is used. So if no autoreleasepool is associated with your thread, the autorelease will not work, leading to memory leak.

The final answer being : If your thread creates object(s) and count on the autorelease mechanism to release them, then you need to create an autoreleasepool for that thread !

Xiomaraxiong answered 28/12, 2010 at 16:54 Comment(5)
I am trying the opposite, to make sure they do not go into the autorelease pool.Strobila
@John Smith: But Apples internal functions also make use of the autorelease pools, so its really hard to avoid them.Rubescent
Exactly ! That's why I always create one for every thread except if I'm sure I don't need it.Xiomaraxiong
so you all mean that create autoreleae pool as soon thread instantiates at least one autoreleaed object?Midlands
@IlkerBaltaci : rephrase please.Xiomaraxiong
C
1

If you don't need a runloop associated with your thread, you'll need to create an autorelease pool manually. I would suggest that for transferring ownership of an object to another thread, you make it explicit rather than trying to rely on autorelease; have some sort of "take ownership" method called on a longer-lived thread that retains it.

Crossjack answered 28/12, 2010 at 22:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.