Which is the best of GCD, NSThread or NSOperationQueue?

Sumitiscreative picture Sumitiscreative · Oct 21, 2012 · Viewed 16.9k times · Source

What's the best way of multithreading in iOS as we have three options GCD, NSThread, and NSOperationQueue? I am confused in which one is the best? If none, then which should be used in what scenario and how they differ and also, if someone has some good example of using NSOperationQueue, please share so that I can learn.

Answer

jkh picture jkh · Oct 22, 2012

Simple answer:

  1. Use NSThread (or even the pthreads API) when you want or need to have direct control over the threads you create, e.g. you need fine-grained control over thread priorities or are interfacing with some other subsystem that vends/consumes thread objects directly and you need to stay on the same page with it. Such instances are rare, but they do occur, particularly in real-time applications.

  2. Use GCD when your task lends itself well to simple parallelization, e.g. you just want to toss some work "into the background" with very little additional work, you have some data structures that you merely wish to serialize access to (and serial queues are great for doing that in a lockless fashion), you have some for loops that would lend themselves well to parallelization with dispatch_apply(), you have some data sources / timers that GCD's sources API will enable you to deal with easily in the background, etc etc. GCD is quite powerful and you can use it for a lot more than this, but these are all relative 'no brainer' scenarios where you don't want to get caught up in the initialization and setup tasks so much as simply "do basic stuff in parallel".

  3. Use NSOperation when you're already up at the Cocoa API layer (vs writing in straight C to the POSIX APIs) and have more complex operations you want to parallelize. NSOperation allows for subclassing, arbitrarily complex dependency graphs, cancellation and a supports a number of other higher-level semantics that may be useful to you. NSOperation actually uses GCD under the covers so it's every bit as multi-core, multi-thread capable as GCD, though it also brings the Foundation framework along for the ride so if you're hacking at the POSIX layer, you probably want to use option #2.

As others have said, however, it all depends on What You Are Trying To Do so there's no single or even universally correct answer to your question.