处理自动释放池和线程

发布于 2024-12-01 19:42:35 字数 406 浏览 1 评论 0原文

如果我创建一个带有回调的线程,例如......

NSAutoreleasePool* pool = [NSAutoreleasePool alloc] init];
while(1) {
   //Process Stuff
}
[pool release];

我假设任何自动释放的东西都不会真正被释放,因为池永远不会耗尽。 我可以将事情更改为这样:

while(1) {
   NSAutoreleasePool* pool = [NSAutoreleasePool alloc] init];
   //Process Stuff
   [pool release];
}

但是如此频繁地分配/删除似乎有点浪费。有没有办法可以留出一块内存并在内存满后释放池?

If I create a thread with a callback like..

NSAutoreleasePool* pool = [NSAutoreleasePool alloc] init];
while(1) {
   //Process Stuff
}
[pool release];

I assume that anything autoreleased will never really be freed since the pool is never drained.
I could change things around to be like this:

while(1) {
   NSAutoreleasePool* pool = [NSAutoreleasePool alloc] init];
   //Process Stuff
   [pool release];
}

But it seems a bit wasteful to alloc/delete so often. Is there a way I can set aside a block of memory and release the pool once its full?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

梦初启 2024-12-08 19:42:35

不用担心,因为Autorelease 很快。你的第二个选择很好。事实上,在 ARC 中,由于新的 @autoreleasepool { } 语法,除了这两个选项之外,很难做任何事情。

Don't worry about it, because Autorelease is Fast. Your second option is fine. And in fact, in ARC, it will be hard to do anything besides those two options because of the new @autoreleasepool { } syntax.

夜深人未静 2024-12-08 19:42:35

如果您在循环的每次迭代中分配了大量的自动释放内存,那么为每次迭代创建并释放一个新的池是正确的做法,以防止内存堆积。

如果您没有生成太多自动释放的内存,那么它不会有什么好处,您只需要外部池。

如果您分配了足够的内存,使得单次迭代无关紧要,但完成时内存已经很多,那么您可以每 X 次迭代创建并释放池。

#define IterationsPerPool 10
NSAutoreleasePool* pool = [NSAutoreleasePool new];
int x = 0;
while(1) {
   //Process Stuff
   if(++x == IterationsPerPool) {
      x = 0;
      [pool release];
      pool = [NSAutoreleasePool new];
   }
}
[pool release];

* 您需要确定什么对您自己来说重要

If you allocate a significant* amount of autoreleased memory in each iteration of your loop, then creating and releasing a new pool for each iteration is the proper thing to do, to prevent the memory from piling up.

If you don't generate much autoreleased memory, then it wouldn't be beneficial and you will only need the outer pool.

If you allocate enough memory that a single iteration is insignificant, but there is a lot by the time you are done, then you could create and release the pool every X iterations.

#define IterationsPerPool 10
NSAutoreleasePool* pool = [NSAutoreleasePool new];
int x = 0;
while(1) {
   //Process Stuff
   if(++x == IterationsPerPool) {
      x = 0;
      [pool release];
      pool = [NSAutoreleasePool new];
   }
}
[pool release];

* You need to determine what significant is for yourself.

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