Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCD, NSOperationQueue, or create a thread manually?

When you use threads, do you have any preferences? In general rule, to use any of these techniques :

  • create a new thread manually and use the run loop
  • use NSOperationQueue
  • or use Grand Central Dispatch and the C version with dispatch_queue?

Does NSOperationQueue simplify everything, and thus is better to be used when we need to create an asynchronous function?

like image 504
Paul Avatar asked Aug 22 '11 10:08

Paul


People also ask

Which is the best of GCD Nsthread or NSOperationQueue?

NSOperationQueue works best when tasks are discrete, synchronous and live in the same thread (eg they are more or less atomic), the queue can be used as basic thread pool though in almost any situation.

What is the difference between NSOperationQueue and GCD?

Grand Central Dispatch is a low-level C API that interacts directly with Unix level of the system. NSOperation is an Objective-C API and that brings some overhead with it. Instances of NSOperation need to be allocated before they can be used and deallocated when they are no longer needed.


2 Answers

I'm lazy, so my philosophy is to pick the simplest solution that does everything I need it to. (I like to think this is the "lazy" espoused by Larry Wall but sometimes I wonder.)

So my order of preference would be:

  1. Asynchronous method calls
  2. NSOperationQueue
  3. Grand Central Dispatch
  4. Thread

There an increase in complexity and flexibility with each step down. If you need the extra flexibility then the complexity is probably worth it.

like image 100
Stephen Darlington Avatar answered Sep 19 '22 00:09

Stephen Darlington


I can remember that in a WWDC 2010 session it was said that GCD is the way to go unless you are working with APIs that currently do not work well with it.

As a general rule, I always use asynchronous method calls for networking and avoid using pthreads or NSThreads directly unless it is absolutely necessary.

like image 39
Sepehr Mahmoudian Avatar answered Sep 18 '22 00:09

Sepehr Mahmoudian