每个线程都需要自己的自动释放池吗?

发布于 2024-10-09 03:28:45 字数 104 浏览 9 评论 0原文

每个线程都必须有自己的池吗?我正在编写一个使用线程的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱她像谁 2024-10-16 03:28:45

不,每个 NSThread 都有自己的 NSRunLoop,但没有自己的 NSAutoreleasePool。因此,您必须创建一个,如果您正在执行大型操作或需要大量时间的操作,您确实应该不时耗尽池以保持较低的内存占用量。

对象存储根本不绑定到线程,您可以从您想要的每个线程访问每个对象,但对象的访问器可能不是线程安全的,从而杀死您的应用程序。但是,这取决于您的应用程序和代码,而不是线程。

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.

偷得浮生 2024-10-16 03:28:45

精确一点 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 !

等风来 2024-10-16 03:28:45

如果您不需要与线程关联的运行循环,则需要手动创建自动释放池。我建议,为了将对象的所有权转移到另一个线程,您应将其明确化,而不是尝试依赖自动释放;有某种“取得所有权”方法,调用保留它的寿命较长的线程。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文