Mac OS X雪豹系统中(iOS4中也新增了GCD)增加了有许多并发机制。除了run loop,线程(包括CocoaPOSIX),Operation之外,雪豹添加了GrandCentral Dispatch (GCD),拥有非常轻量级的工作单元和并发方式,并且由系统决定其最佳调度方式。









When to use NSOperation vs. GCD

Mac OS X has a number of concurrency mechanisms, and thatincreases with Snow Leopard. In addition to run loops, threads (both Cocoa andPOSIX) and operations, Snow Leopard addsGrand Central Dispatch (GCD), avery lightweight way to represent units of work and the style of concurrencythey need, and have the system figure out how to schedule them.

But wait, don’t we have that already in NSOperation? Itshouldn’t surprise you in the least to learn that NSOperation, on Snow Leopard,is built atop GCD. However, there are a number of differences between the two,and for that reason people have started to ask “How should I decide which touse when?”

The straightforward answer is a general guideline for allapplication development:

Always use the highest-level abstractionavailable to you, and drop down to lower-level abstractions when measurementshows that they are needed.

In this particular case, it means that when writing Cocoaapplications, you should generally be using NSOperation rather than using GCDdirectly. Not because of a difference in efficiency, but because NSOperationprovides a higher-level abstraction atop the mechanisms of GCD.

For example, you can set up a dependency between twoNSOperations such that the second will only be run after the first is complete— even if they’re run on different queues. You can use KVO to observe thecompletion (or cancellation) of different operations — and you can createoperations that support being cancelled in the first place. You can set acompletion block to run after an application has finished. And you can, ofcourse, create operations from blocks using NSBlockOperation.

You’ll also fit in better with Cocoa by using NSOperationin your high-level code. If you take a look at new Snow Leopard API onNSNotificationCenter, you’ll see one where you specify the NSOperationQueue onwhich you wish a notification to run a block.

Ultimately, you spend a little bit ofoverhead to use NSOperation instead of GCD, but you gain significant additionalfunctionality that will be useful as you start to compose operations together.And that’s the biggest benefit of NSOperation: You can break up yourapplication in terms of units of work that can not only be run on a queue, butalso canceled, observed, and depended upon. This lets you easily define yourdata dependencies and ensure that you aren’t simply running code serially as aside-effect of locking.


©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
钱包余额 0