Concurrency and NSOperation

Multithreading implementations vary a lot, from low-level APIs (like POSIX pthread) to very high-level, which are built on top of low=level and they are friendlier and easier to use. In this respect, NSOperation is higher than GCD, which still has a lot of complexity.

What is what?

  • Thread – a unit of execution, generally expected to share memory and other resources with other threads and managed independently by operating system scheduler. Every UI code runs on main thread.
  • Process – instance of program that is being executed. One process can have one or many threads.
  • Concurrent operation – takes place in a different thread than the one it was started in.
  • Condition – will prevent thread from processing if not met. Used for synchronisation purposes.
  • Critical section – piece of code that access shared resource that must not be accessed by more than one thread.
  • Mutex – “lock”, requirement to ensure that no two concurrent threads are in their critical section at the same time. Mutexes and conditions are examples of Semaphore – protected variable that restricts access to a shared resource.


Operation objects are instances of NSOperation and they encapsulate code that we want to perform. To use NSOperation, we must subclass it. There are two subclasses available, and being used most of the time. For special cases, we can create our own subclasses.
NSInvocationOperation – instantiated by using already existing object and selector from an application.
NSBlockOperation – can use this class to execute various block objects at once.

Features of operation objects:

  • Dependencies – can make an operation execute after another one had finished.
  • Optional completion blocks
  • Prioritizing tasks
  • Any operation can be cancelled at any time
  • Operations commonly are executed by adding them to queue.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s