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?
Concurrencyis dividing up theexecution pathsof 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
NSOperationQueueclass regulates the execution of a set ofNSOperationObjects. AnOperationQueueis generally used to perform someasynchronousoperations on abackgroundthread and not to block themain thread.
NSBlockOperationallows you to create anNSOperationfrom one or more closures.NSBlockOperationscan 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 abackgroundqueue when some background processing has finished and the user interface needs to be updated. Acustom dispatchqueue 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
NSOperationsQueueandGCDallow executingheavy computationtask in the background on separate threads by freeing theUI Application MainTread.
- OperationQueue - If you’re working with objects that need to encapsulate data and functionality then you’re more likely to utilize Operations. -
NSOperationandNSOperationQueueare high-level Objective-C classes. -InstancesofNSOperationneed to be allocated before they can be used and deallocated when they are no longer needed. Even though this is a highly optimized process -NSOperationslightly shower than GCD.
DependenciesTheNSOperationAPI provides support for dependencies. This is a powerful concept that enables developers to execute tasks in a specific order. Anoperationis ready when every dependency has finished executing.ObservableTheNSOperationandNSOperationQueueclasses 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,ResumeOperationscan bepaused,resumed, andcancelled. Once you dispatch a task usingGrand Central Dispatch, you no longer have control or insight into the execution of that task. TheNSOperationAPI is more flexible in that respect, giving the developer control over the operation's life cycle.
What is a Serial Queue?
A
Serial queueallows us to perform only one task at a time, no matter theway of execution, i.e.SynchronousorAsynchronous. 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 queuehelps 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-offandstartsa runloop on the main thread, one can begin taking advantage ofQoS.QoSbreaks outprioritiesinto 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 theseasynchronoustasks 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 visibleto 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 threador theUI thread.
What is Dispatch Group?
If we need to wait on a couple of
asynchronousorsynchronousoperations before proceeding, we can use DispatchGroup.
Global dispatch queue?
Tasksinconcurrentqueue 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
synchronousrequests themain thread gets blockedandcontrolwill not get back to the user till that request gets executed.Asynchronouscontrol gets back to the user even if a request is getting executed.
What is NSThread?
NSThreadwhen 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 inUIElements. 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 typesandreference types. they are pretty fast when compared toDynamic dispatchas 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 offinalandstaticas both of them ensures that theclass and methodcannot beoverridden.
Dynamic Dispatchis supported only byreference types.dynamic dispatch, in short, we needinheritanceand 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
Semaphoreis 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 threadsdoing 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"