NSOperation 是否会产生一个新线程?
很简单,线程(或 NSThread)和 NSOperation 之间是否存在一对一的连接?或者它是否抽象出一个操作,是一种可以由后台多个线程拾取和运行的任务?
Very simply, is there a one to one connection between a thread(or NSThread) and an NSOperation? Or is it abstracted out an operation is kind of a task that can be picked up and run by multiple threads in the background?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不是一对一的连接,不是。使用 NSOperation 子类的优点是您不需要自己管理多线程。 Apple 甚至(令人困惑地)将典型的
NSOperation
子类(即覆盖-main
方法的子类)定义为非并发,而不是因为它不不支持并发,但因为并发的细节是由超类管理的:从这个意义上说,
NSOperation
子类更像是 NSThread 的目标对象detachNewThreadSelector:toTarget:withObject:
。如果您想控制并发行为的方式,另一种方法是在调用
-main
之前覆盖-start
并根据需要设置并发。这是一个非常好的概述:Managing Concurrency with NSOperation
Not a one-to-one connection, no. The advantage of using
NSOperation
subclasses is that you're not required to manage the multi-threading yourself. Apple even (confusingly) defines the typicalNSOperation
subclass (i.e., one overriding the-main
method) as non-concurrent, not because it doesn't support concurrency, but because the details of concurrency are managed by the superclass:In that sense, an
NSOperation
subclass is much more like the target object of NSThread'sdetachNewThreadSelector:toTarget:withObject:
.The alternative, if you want control over how the concurrency behaves, is to override
-start
and set up concurrency as needed before invoking-main
.Here's a very good overview: Managing Concurrency with NSOperation