Dispatch Queues In iOS Swift.

Santosh Kumar J M
2 min readMar 10, 2021

Dispatch, also known as Grand Central Dispatch (GCD), contains language features, runtime libraries, and system enhancements that provide systemic, comprehensive improvements to the support for concurrent code execution on multicore hardware in macOS, iOS, watchOS, and tvOS.

What is Dispatch Queue?

An object that manages the execution of tasks serially or concurrently on your app’s main thread or on a background thread.

Dispatch queues are FIFO queues to which your application can submit tasks in the form of block objects. Dispatch queues execute tasks either serially or concurrently.

You schedule work items synchronously or asynchronously. When you schedule a work item synchronously, your code waits until that item finishes execution. When you schedule a work item asynchronously, your code continues executing while the work item runs elsewhere.

  • Creating Serial Queue
    Serial queues
    execute one task at a time in the order in which they are added to the queue.
let serialQueue = DispatchQueue(label: “com.queue.serial”)serialQueue.async {print(“serialQueue Task 1 started”)// Do your work..print(“serialQueue Task 1 finished”)}serialQueue.async {print(“serialQueue Task 2 started”)// Do your work..print(“serialQueue Task 2 finished”)}

Example:- Imagine you are standing in the queue to buy a movie, ticket the movie ticket will be given to the person who is standing in the first and then to the another person. In the same way, serialQueue executes whichever task is assigned first.

Creating ConcurrentQueue
Concurrent queues execute one or more tasks concurrently, but tasks are still started in the order in which they were added to the queue.

let concurrentQueue = DispatchQueue(label: "com.queue.concurrent", attributes: .concurrent)concurrentQueue.async {print("concurrentQueue Task 1 started")// Do your work..print("concurrentQueue Task 1 finished")}concurrentQueue.async {print("concurrentQueue Task 2 started")// Do your work..print("concurrentQueue Task 2 finished")}

Example:- Imagine the running-race all the persons will start at a time but we cannot judge who comes first. In the same way, concurrent queues works.

  • Creating main queue asynchronously

Asynchronous queue runs the task in the background it doesn’t wait for the task to complete.

DispatchQueue.main.async {//Do your work..}
  • Creating main queue synchronously

Synchronous queue waits until the task is completed.

DispatchQueue.main.sync {//Do your work..}

--

--