NSOperation 是否会产生一个新线程?

发布于 2024-11-06 19:03:55 字数 86 浏览 2 评论 0原文

很简单,线程(或 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 技术交流群。

扫码二维码加入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 typical NSOperation 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:

Don’t be confused by the terminology: just because an operation is non-concurrent, does not mean it cannot be executed concurrently, it simply means that you don't have to handle the concurrency yourself.

In that sense, an NSOperation subclass is much more like the target object of NSThread's
detachNewThreadSelector: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

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