Grand Central Dispatch vs NSThreads?
I searched a variety of sources but don’t really understand the difference between using
NSThreads and GCD. I’m completely new to the OS X platform so I might be completely misinterpreting this.
From what I read online, GCD seems to do the exact same thing as basic threads (POSIX,
NSThreads etc.) while adding much more technical jargon (“blocks”). It seems to just overcomplicate the basic thread creation system (create thread, run function).
What exactly is GCD and why would it ever be preferred over traditional threading? When should traditional threads be used rather than GCD? And finally is there a reason for GCD’s strange syntax? (“blocks” instead of simply calling functions).
I am on Mac OS X 10.6.8 Snow Leopard and I am not programming for iOS – I am programming for Macs. I am using Xcode 3.6.8 in Cocoa, creating a GUI application.
- AVAudioPlayer on OS X not playing any sound
- Iterating through files in a folder with nested folders - Cocoa
- How to use UCKeyTranslate
- xcode sqlite3 libsqlite.dylib
- NSTextField - White text on black background, but black cursor
- Building a Mac OS X/Cocoa application for distribution with an imported framework
4 Solutions Collect From Internet About “Grand Central Dispatch vs NSThreads?”
Advantages of Dispatch
The advantages of dispatch are mostly outlined here:
Migrating Away from Threads
The idea is that you eliminate work on your part, since the paradigm fits MOST code more easily.
- It reduces the memory penalty your application pays for storing thread stacks in the application’s memory space.
- It eliminates the code needed to create and configure your threads.
- It eliminates the code needed to manage and schedule work on threads.
- It simplifies the code you have to write.
Empirically, using GCD-type locking instead of
@synchronized is about 80% faster or more, though micro-benchmarks may be deceiving. Read more here, though I think the advice to go async with writes does not apply in many cases, and it’s slower (but it’s asynchronous).
Advantages of Threads
Why would you continue to use Threads? From the same document:
It is important to remember that queues are not a panacea for
replacing threads. The asynchronous programming model offered by
queues is appropriate in situations where latency is not an issue.
Even though queues offer ways to configure the execution priority of
tasks in the queue, higher execution priorities do not guarantee the
execution of tasks at specific times. Therefore, threads are still a
more appropriate choice in cases where you need minimal latency, such
as in audio and video playback.
Another place where I haven’t personally found an ideal solution using queues is daemon processes that need to be constantly rescheduled. Not that you cannot reschedule them, but looping within a NSThread method is simpler (I think). Edit: Now I’m convinced that even in this context, GCD-style locking would be faster, and you could also do a loop within a GCD-dispatched operation.
Blocks in Objective-C?
Blocks are really horrible in Objective-C due to the awful syntax (though Xcode can sometimes help with autocompletion, at least). If you look at blocks in Ruby (or any other language, pretty much) you’ll see how simple and elegant they are for dispatching operations. I’d say that you’ll get used to the Objective-C syntax, but I really think that you’ll get used to copying from your examples a lot 🙂
You might find my examples from here to be helpful, or just distracting. Not sure.
While the answers so far are about the context of threads vs GCD inside the domain of a single application and the differences it has for programming, the reason you should always prefer GCD is because of multitasking environments (since you are on MacOSX and not iOS). Threads are ok if your application is running alone on your machine. Say, you have a video edition program and want to apply some effect to the video. The render is going to take 10 minutes on a machine with eight cores. Fine.
Now, while the video app is churning in the background, you open an image edition program and play with some high resolution image, decide to apply some special image filter and your image application being clever detects you have eight cores and starts eight threads to process the image. Nice isn’t it? Except that’s terrible for performance. The image edition app doesn’t know anything about the video app (and vice versa) and therefore both will request their respectively optimum number of threads. And there will be pain and blood while the cores try to switch from one thread to another, because to avoid starvation the CPU will eventually let all threads run, even though in this situation it would be more optimal to run only 4 threads for the video app and 4 threads for the image app.
For a more detailed reference, take a look at http://deusty.blogspot.com/2010/11/introducing-gcd-based-cocoahttpserver.html where you can see a benchmark of an HTTP server using GCD versus thread, and see how it scales. Once you understand the problem threads have for multicore machines in multi-app environments, you will always want to use GCD, simply because threads are not always optimal, while GCD potentially can be since the OS can scale thread usage per app depending on load.
Please, remember we won’t have more GHz in our machines any time soon. From now on we will only have more cores, so it’s your duty to use the best tool for this environment, and that is GCD.
Blocks allow for passing a block of code to execute. Once you get past the “strange syntax”, they are quite powerful.
GCD also uses queues which if used properly can help with lock free concurrency if the code executing in the separate queues are isolated. It’s a simpler way to offer background and concurrency while minimizing the chance for deadlocks (if used right).
The “strange syntax” is because they chose the caret (^) because it was one of the few symbols that wasn’t overloaded as an operator in C++
When it comes to adding concurrency to an application, dispatch queues
provide several advantages over threads. The most direct advantage is
the simplicity of the work-queue programming model. With threads, you
have to write code both for the work you want to perform and for the
creation and management of the threads themselves. Dispatch queues let
you focus on the work you actually want to perform without having to
worry about the thread creation and management. Instead, the system
handles all of the thread creation and management for you. The
advantage is that the system is able to manage threads much more
efficiently than any single application ever could. The system can
scale the number of threads dynamically based on the available
resources and current system conditions. In addition, the system is
usually able to start running your task more quickly than you could if
you created the thread yourself.
Although you might think rewriting your code for dispatch queues would
be difficult, it is often easier to write code for dispatch queues
than it is to write code for threads. The key to writing your code is
to design tasks that are self-contained and able to run
asynchronously. (This is actually true for both threads and dispatch
Although you would be right to point out that two tasks running in a
serial queue do not run concurrently, you have to remember that if two
threads take a lock at the same time, any concurrency offered by the
threads is lost or significantly reduced. More importantly, the
threaded model requires the creation of two threads, which take up
both kernel and user-space memory. Dispatch queues do not pay the same
memory penalty for their threads, and the threads they do use are kept
busy and not blocked.
GCD (Grand Central Dispatch): GCD provides and manages FIFO queues to which your application can submit tasks in the form of block objects. Work submitted to dispatch queues are executed on a pool of threads fully managed by the system. No guarantee is made as to the thread on which a task executes. Why GCD over threads :
How much work your CPU cores are doing
How many CPU cores you have.
How much threads should be spawned.
If GCD needs it can go down into the kernel and communicate about resources, thus better scheduling.
Less load on kernel and better sync with OS
GCD uses existing threads from thread pool instead of creating and then destroying.
Best advantage of the system’s hardware resources, while allowing the operating system to balance the load of all the programs currently running along with considerations like heating and battery life.
I have shared my experience with threads, operating system and GCD AT http://iosdose.com
- SWIFT rotating an image in an UIImageview defined in the Main.storyboard
- Asynchronous loading – UITableView and Firebase
- nth prime number in swift
- MKMapView using a lot of memory each time i load its view
- iOS – Subclassing MFMessageComposeViewController to add extra functionality
- iOS – How can I preload the keyboard?
- Is it safe to rely on NSUbiquitousKeyValueStore for storing essential data?
- Google Sign In Button does Nothing
- How to decode a property with type of JSON dictionary in Swift 4 decodable protocol
- Is – asynchronous or synchronous?
- Custom “resizable image” drawing in iOS
- Specify type of polymorphic function to pass it as argument
- Play iPod playlist retrieved from a saved persistentid list
- Swift Send Email with MailGun
- swift segue not passing data from tableview