Objective C - NSthread 和 NSthread NSAutoreleasePool?
编写线程安全方法的最佳方法是什么?
我有以下方法,有时我想异步调用它(通过线程调用它) 有时我想直接在主线程上调用它。 即使我没有在单独的线程上调用该方法,保留池(分配、释放)是否存在问题?
- (void)doStuff
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
//do some stuff here?
[pool release];
}
What is the best way to write a thread safe method?
I have the following method, sometimes i want to call it asynchronously (call it through a thread)
And sometimes i want to call it directly on the main thread.
Is there a problem with keeping the pool (alloc, release) even if I am not calling the method on a separate thread?
- (void)doStuff
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
//do some stuff here?
[pool release];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在主线程上调用是完全安全的。 NSAutoreleasePool 维护一个堆栈,因此在这种情况下,您只需将一个新池放在堆栈顶部,然后在完成后将其弹出。
That's perfectly safe to call on the main thread. NSAutoreleasePool maintains a stack, so in this case you're just putting a new pool on top of the stack, then popping it off when you're done.
不,始终使用您自己的方法本地池没有问题。不过,您应该使用
[pool排出]
而不是[poolrelease]
。No, there is no problem with always using your own, method-local pool. You should be using
[pool drain]
instead of[pool release]
, though.不管这对发布池意味着什么,我都不建议这样写。如果您绝对必须能够从主线程和其他线程调用该方法,请按如下方式编码:
这样您就可以将该方法包装在负责释放池的方法中。
Regardless of what it would mean for the release pool, I would not recommend writing it this way. If you absolutely have to be able to call the method from the main and from other threads, code it like this:
This way you wrap the method in a method that takes care of the release pool.
我也更喜欢 Ivo Jansch 提到的方法。创建/排出池是有效的,但是当您递归或多次调用方法 doStuff: 时可能会有点头痛。但通过遵循 Ivo 的方法,你可以做一些事情而不会出现记忆问题。
而且,为了使方法是线程安全的,您必须在需要时使用锁或@synchronized(),通常是在访问数组/缓冲区/字典时。你的方法应该是这样的
I will also prefer the method mentioned by Ivo Jansch. Creating/draining a pool is valid but it may be a bit headache when you call the method doStuff: recursively or many times. But by following Ivo's method you can do stuff without a memory headache.
And also for a method to be thread safe you must use locks or @synchronized() whenever its needed, usually when accessing a array/buffer/dictionary. Your method should be something like this