每个线程都需要自己的自动释放池吗?
每个线程都必须有自己的池吗?我正在编写一个使用线程的 iPhone 应用程序。如果我不在线程上放置一个池,它就会抱怨泄漏。
我想做的是存储一些比线程寿命更长的对象。我该怎么做呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,每个
NSThread
都有自己的NSRunLoop
,但没有自己的NSAutoreleasePool
。因此,您必须创建一个,如果您正在执行大型操作或需要大量时间的操作,您确实应该不时耗尽
池以保持较低的内存占用量。对象存储根本不绑定到线程,您可以从您想要的每个线程访问每个对象,但对象的访问器可能不是线程安全的,从而杀死您的应用程序。但是,这取决于您的应用程序和代码,而不是线程。
No, every
NSThread
has its ownNSRunLoop
, but not its ownNSAutoreleasePool
. 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 shoulddrain
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.
精确一点 JustSid 所说的:当对对象调用 autorelease 时,将使用与当前线程关联的 autoreleasepool。因此,如果没有自动释放池与您的线程关联,则自动释放将不起作用,从而导致内存泄漏。
最终答案是:如果您的线程创建对象并依靠自动释放机制来释放它们,那么您需要为该线程创建一个自动释放池!
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 !
如果您不需要与线程关联的运行循环,则需要手动创建自动释放池。我建议,为了将对象的所有权转移到另一个线程,您应将其明确化,而不是尝试依赖自动释放;有某种“取得所有权”方法,调用保留它的寿命较长的线程。
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.