GCD (Grand Central Dispatch) - Imtiaz211/interviews GitHub Wiki
Grand Central Dispatch?
GCD is an extremely important feature introduced in iOS 4.0, OS X 10.6 and later versions. Barrier and semaphor are used for pause, and play. groupworkItem used for cancel the API call. GCD works with blocks, which are blocks of code that you need to execute in the background, low, default and high priority queue, in a serial or concurrent order.
What is Concurrency?
Concurrency
is dividing up theexecution paths
of your program so that they are possibly running at thesame time
. The common terminology:process
,thread
,multithreading
, andothers
. Terminology;Process
, An instance of an executing appThread
, Path of execution for codeMultithreading
, Multiple threads or multiple paths of execution running at the same time.Concurrency
, Execute multiple tasks at the same time in a scalable manner.Queues
, Queues are lightweight data structures that manage objects in the order of First-in, First-out (FIFO).
NSOperationQueue?
The
NSOperationQueue
class regulates the execution of a set ofNSOperationObjects
. AnOperationQueue
is generally used to perform someasynchronous
operations on abackground
thread and not to block themain thread
.
NSBlockOperation
allows you to create anNSOperation
from one or more closures.NSBlockOperations
can have multiple blocks that run concurrently.
Main dispatch queue?
Available serial queue that executes tasks on the application's
main thread
. It is usually called from abackground
queue when some background processing has finished and the user interface needs to be updated. Acustom dispatch
queue that schedules tasks for serial execution on an arbitrary thread.
Difference between GCD and Operation?
- GCD - methods or chunks of code that need to be executed, GCD is a fitting choice. - GCD is a low-level C-based API that interacts directly with the Unix level of the system. - Both
NSOperationsQueue
andGCD
allow executingheavy computation
task in the background on separate threads by freeing theUI Application Main
Tread.
- OperationQueue - If you’re working with objects that need to encapsulate data and functionality then you’re more likely to utilize Operations. -
NSOperation
andNSOperationQueue
are high-level Objective-C classes. -Instances
ofNSOperation
need to be allocated before they can be used and deallocated when they are no longer needed. Even though this is a highly optimized process -NSOperation
slightly shower than GCD.
Dependencies
TheNSOperation
API provides support for dependencies. This is a powerful concept that enables developers to execute tasks in a specific order. Anoperation
is ready when every dependency has finished executing.Observable
TheNSOperation
andNSOperationQueue
classes have a number of properties that can be observed, using KVO (Key Value Observing). This is another important benefit if you want tomonitor the state of an operation or operation queue
.Pause
,Cancel
,Resume
Operations
can bepaused
,resumed
, andcancelled
. Once you dispatch a task usingGrand Central Dispatch
, you no longer have control or insight into the execution of that task. TheNSOperation
API is more flexible in that respect, giving the developer control over the operation's life cycle.
What is a Serial Queue?
A
Serial queue
allows us to perform only one task at a time, no matter theway of execution
, i.e.Synchronous
orAsynchronous
. All the queues need to wait for the completion of the previous queue. By default, DispatchQueue is a serial queue.
What is a Concurrent Queue?
A
concurrent queue
helps us execute multiple tasks at the same time, but there’s a limit to the number of tasks depending on the system. If used incautiously, it can cause Thread explosion and Deadlock.
Quality of Service?
After an app
kicks-off
andstarts
a runloop on the main thread, one can begin taking advantage ofQoS
.QoS
breaks outpriorities
into four different groups. Each one corresponds to common tasks one might find themselves coding in their iOS endeavors.
User Interactive
: Work that happens on themain thread
, such as animations or drawing operations. highest periorityUser Initiated
: The user initiates theseasynchronous
tasks from the UI, Work that the user kicks-off and should yield immediate results. This work must be completed for the user to continue.Utility
: Work that may take abit and doesn’t need to finish right away
. Analogous to progress bars and importing data.Background
: This workisn’t visible
to the user. Backups, syncs, indexing, etc. lowest periorityDefault
: this quality of service periority falls between User Initiated or UtilityUnspecified
: Thread can have unspecified QoS.
At launch time which queue use system?
When the app launches, it will be on the
main thread
or theUI thread
.
What is Dispatch Group?
If we need to wait on a couple of
asynchronous
orsynchronous
operations before proceeding, we can use DispatchGroup.
Global dispatch queue?
Tasks
inconcurrent
queue executed concurrently[background threads]
. Tasks are still started in the order that they were added to the queue.
Enlist the methods to achieve concurrency in iOS?
- Threads.
- Dispatch queues.
- Operation Queues.
What is synchronous and asynchronous request?
In
synchronous
requests themain thread gets blocked
andcontrol
will not get back to the user till that request gets executed.Asynchronous
control gets back to the user even if a request is getting executed.
What is NSThread?
NSThread
when you want a unit of computational work done without necessarily either waiting for other units to finish, or holding up other computational work. And don’t use it inUI
Elements. All UI Elements happened on theMain thread
. It creates a new low level thread which can be started by calling like, [myThread start];
Static and Dynamic Dispatch ?
Static Dispatch
(or Direct Dispatch) is supported by bothvalue types
andreference types
. they are pretty fast when compared toDynamic dispatch
as the compiler is able to locate where the instructions are, at compile time. So, when the function is called, the compiler jumps directly to the memory address of the function to perform the operation. we need to make use offinal
andstatic
as both of them ensures that theclass and method
cannot beoverridden
.
Dynamic Dispatch
is supported only byreference types
.dynamic dispatch
, in short, we needinheritance
and our value types do not support inheritance. The implementationis chosen at runtime instead of compile-time, which adds some overhead. it allows polymorphism to exist.
Semaphore
Semaphore
is part of dispatch framework hence it is begin with word dispatch- DispatchWorkItem()
- DispatchSemaphore()
- DispatchGroup()
- Semaphore is a object to control the access of shared resources"
dispatch_once()?
dispatch_once()
is absolutelysynchronous
. Not all GCD methods do thingsasynchronously
(case in point,dispatch_sync()
issynchronous
). The benefit ofdispatch_once()
over this is that it's faster. It's also semantically cleaner, because it also protects you frommultiple threads
doing alloc init of your shared Instance--if they all try at the same exact time.It won't allow two instances to be created. The entire idea of dispatch_once() is "perform something once and only once"