Why do we need to use NSAutoreleasepool for each thread?

In iOS app development, we are using NSAutoreleasePool to relinquish ownership of objects at a later point in time.

But why can it be shared between different threads?

Why do we need to create a new autoreleasepool when I wanted to use a new thread?

EDIT:

As taskinoor mentioned my question was why this is designed in such a way that each thread should have a separate autoreleasepool.

Answers


The design challenge for multi-thread autorelease pools is when to drain them. If you drain the pool while an object is still being used, then you will crash. Per thread, it's easy to tell when you are outside the run loop and thus at a point where autoreleased objects can be drained. In a multi-thread situation, your threads would need to be synchronized at the end of their runloop so you can be sure you are at a safe point to drain them. Synchronized treads in this way is a bad idea, it creates lots of idle time and slows down the program.


Each thread is a different execution context - one thread may exit sooner or later, they might use different resources with different lifetimes and memory managementt needs, so each thread should be managed independently.


Because they designed in this way. I guess your question is why they designed in this way. I am not 100% sure, but one possible reason may be that sharing a resource across threads has its cost. During every modification to the shared pool each thread will need to lock-unlock that which will reduce the performance. A resource should be shared across multiple threads only if that sharing is necessary which is not the case with autorelease pools. Using dedicated autorelease pool will perform better. This could be one possible reason for this design decision.


I don't think the autorelease pools are shared between threads, according to apples memory management guide in Cocoa each thread has its own stack of autorelease pools

If you don't create an autorelease pool for threads which you create or detach, then the autorelease function doesnt work, so the memory footprint will grow


Need Your Help

WCF Custom Message Writing With Transaction Support

wcf transactions message msdtc distributed-transactions

I'm using a custom message that inherits the System.Servicemodel.Channels.Message.

How to insulate a job/thread from crashes

c++ multithreading crash signals longjmp

I'm working on a library where I'm farming various tasks out to some third-party libraries that do some relatively sketchy or dangerous platform-specific work. (In specific, I'm writing a mathemat...