Swift 3
Dispatch Queue
Swift Programming
Concurrency
iOS Development

How to create dispatch queue in Swift 3

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In Swift 3, handling concurrency effectively is crucial for creating responsive and efficient applications. Dispatch queues are an essential part of Apple's Grand Central Dispatch (GCD), enabling developers to execute tasks asynchronously and manage app resources better. This article delves into creating dispatch queues in Swift 3, providing technical insights and examples to guide you through the process.

Understanding Dispatch Queues

Dispatch queues manage the execution of tasks either serially or concurrently. They come in two types:

  1. Serial Queues: These ensure tasks execute one at a time in the order they are added.
  2. Concurrent Queues: These permit multiple tasks to execute simultaneously.

Swift's GCD provides both global concurrent queues and custom queues.

Key Concepts

  • Synchronous vs Asynchronous Execution:
    • Synchronous: The system waits for the task to finish before moving on.
    • Asynchronous: Tasks are dispatched and run independently as the system continues executing subsequent code.
  • Main Queue:
    • Runs on the main thread, handling UI updates. Always serial.
  • Global Queues:
    • Shared system-provided concurrent queues, available for background tasks.

Creating a Dispatch Queue

1. Serial Queue

Serial queues are beneficial when tasks require sequential execution. Here's a basic example of creating and using a serial dispatch queue:

swift
1let serialQueue = DispatchQueue(label: "com.example.serialQueue")
2
3serialQueue.async {
4    print("Task 1 - Executed first")
5}
6
7serialQueue.async {
8    print("Task 2 - Executed second")
9}

In this code, Task 1 will always run before Task 2, even though they are dispatched asynchronously.

2. Concurrent Queue

For scenarios requiring concurrent execution, custom concurrent dispatch queues can be created:

swift
1let concurrentQueue = DispatchQueue(label: "com.example.concurrentQueue", attributes: .concurrent)
2
3concurrentQueue.async {
4    print("Concurrent Task 1")
5}
6
7concurrentQueue.async {
8    print("Concurrent Task 2")
9}

Task 1 and Task 2 can execute simultaneously, depending on system resources.

Utilizing Global Dispatch Queues

Global dispatch queues are system-managed concurrent queues, ideal for non-UI work that doesn't require customization:

swift
1DispatchQueue.global(qos: .background).async {
2    // Background task
3    let sum = (1...1000).reduce(0, +)
4    print("Sum: \(sum)")
5}

Specifying the quality of service (QoS) allows prioritization of tasks, influencing their execution priority.

Quality of Service Classes

  • userInteractive: Tasks related to UI updates.
  • userInitiated: Immediate tasks initiated by the user.
  • utility: Long-running tasks with a visible process indicator.
  • background: Tasks that are not time-sensitive.

Synchronization

Occasionally, synchronization across different queues is necessary to maintain data consistency. Using barriers with concurrent queues ensures exclusive access:

swift
1concurrentQueue.async(flags: .barrier) {
2    // Exclusive write operation
3    sharedResource.append("New Data")
4}

Barriers ensure that the block doesn't execute until all tasks submitted before it have finished.

Applying Dispatch Queues

Example: Image Processing

Consider an app that downloads and processes images concurrently:

swift
1let imageQueue = DispatchQueue(label: "com.example.imageQueue", qos: .userInitiated, attributes: .concurrent)
2
3func fetchImage(from url: URL, completion: @escaping (Image?) -> Void) {
4    imageQueue.async {
5        guard let data = try? Data(contentsOf: url) else { 
6            completion(nil)
7            return
8        }
9        completion(Image(data: data))
10    }
11}
12
13fetchImage(from: url) { image in
14    DispatchQueue.main.async {
15        // Update UI with the image
16        imageView.image = image
17    }
18}

This example demonstrates fetching and processing images on a concurrent queue while ensuring UI updates occur on the main queue.

Summary

The table below outlines the core concepts and attributes related to dispatch queues:

ConceptDescription
Main QueueRuns on the main thread for UI updates. Serial execution.
Serial QueueCustom queue with sequential execution.
Concurrent QueueCustom or global queue allowing simultaneous execution.
SynchronousBlocks further execution until task completion.
AsynchronousDispatches tasks without blocking subsequent code.
Quality of ServicePrioritizes task execution (userInteractive, userInitiated, utility, background).
BarriersEnsures exclusive access for write operations on concurrent queues.

Understanding and utilizing dispatch queues efficiently allow for better resource management, resulting in highly responsive applications. By diving deeper into advanced techniques like synchronization and QoS, developers can further optimize their application's performance with GCD in Swift 3.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.