Friday, November 6, 2026
HomeiOS DevelopmentFinal Grand Central Dispatch tutorial in Swift

Final Grand Central Dispatch tutorial in Swift

[ad_1]

Be taught the rules of multi-threading with the GCD framework in Swift. Queues, duties, teams all the pieces you will ever want I promise.

iOS

GCD concurrency tutorial for newbies

The Grand Central Dispatch (GCD, or simply Dispatch) framework relies on the underlying thread pool design sample. Which means that there are a hard and fast variety of threads spawned by the system – primarily based on some components like CPU cores – they’re at all times obtainable ready for duties to be executed concurrently. 🚦

Creating threads on the run is an costly job so GCD organizes duties into particular queues, and afterward the duties ready on these queues are going to be executed on a correct and obtainable thread from the pool. This method results in nice efficiency and low execution latency. We will say that the Dispatch framework is a really quick and environment friendly concurrency framework designed for contemporary multicore hardwares and desires.

Concurrency, multi-tasking, CPU cores, parallelism and threads

A processor can run duties made by you programmatically, that is often known as coding, growing or programming. The code executed by a CPU core is a thread. So your app goes to create a course of that’s made up from threads. 🤓

Previously a processor had one single core, it might solely take care of one job at a time. Afterward time-slicing was launched, so CPU’s might execute threads concurrently utilizing context switching. As time handed by processors gained extra horse energy and cores in order that they had been able to actual multi-tasking utilizing parallelism. ⏱

These days a CPU is a really highly effective unit, it is able to executing billions of duties (cycles) per second. Due to this excessive availability velocity Intel launched a know-how known as hyperthreading. They divided CPU clock cycles between (often two) processes operating on the similar time, so the variety of obtainable threads primarily doubled. 📈

As you’ll be able to see concurrenct execution might be achieved with varied strategies, however you needn’t care about that a lot. It is as much as the CPU structure the way it solves concurrency, and it is the working system’s job how a lot thread goes to be spawned for the underlying thread pool. The GCD framework will cover all of the complexity, nevertheless it’s at all times good to know the essential rules. 👍


Synchronous and asynchronous execution

Every work merchandise might be executed both synchronously or asynchronously.

Have you ever ever heard of blocking and non-blocking code? This is similar situaton right here. With synchronous duties you will block the execution queue, however with async duties your name will immediately return and the queue can proceed the execution of the remaining duties (or work objects as Apple calls them). 🚧

Synchronous execution

When a piece merchandise is executed synchronously with the sync methodology, this system waits till execution finishes earlier than the tactic name returns.

Your operate is most probably synchronous if it has a return worth, so func load() -> String goes to in all probability block the factor that runs on till the assets is totally loaded and returned again.

Asynchronous execution

When a piece merchandise is executed asynchronously with the async methodology, the tactic name returns instantly.

Completion blocks are a great sing of async strategies, for instance in case you take a look at this methodology func load(completion: (String) -> Void) you’ll be able to see that it has no return kind, however the results of the operate is handed again to the caller afterward by way of a block.

This can be a typical use case, if it’s a must to look ahead to one thing inside your methodology like studying the contents of an enormous file from the disk, you do not need to block your CPU, simply due to the gradual IO operation. There might be different duties that aren’t IO heavy in any respect (math operations, and many others.) these might be executed whereas the system is studying your file from the bodily arduous drive. 💾

With dispatch queues you’ll be able to execute your code synchronously or asynchronously. With syncronous execution the queue waits for the work, with async execution the code returns instantly with out ready for the duty to finish. ⚡️


Dispatch queues

As I discussed earlier than, GCD organizes job into queues, these are identical to the queues on the shopping center. On each dispatch queue, duties can be executed in the identical order as you add them to the queue – FIFO: the primary job within the line can be executed first – however you must observe that the order of completion will not be assured. Duties can be accomplished in accordance with the code complexity. So in case you add two duties to the queue, a gradual one first and a quick one later, the quick one can end earlier than the slower one. ⌛️

Serial and concurrent queues

There are two varieties of dispatch queues. Serial queues can execute one job at a time, these queues might be utilized to synchronize entry to a particular useful resource. Concurrent queues then again can execute a number of duties parallell in the identical time. Serial queue is rather like one line within the mall with one cashier, concurrent queue is like one single line that splits for 2 or extra cashiers. 💰

Primary, world and customized queues

The major queue is a serial one, each job on the primary queue runs on the primary thread.

World queues are system supplied concurrent queues shared by way of the working system. There are precisely 4 of them organized by excessive, default, low precedence plus an IO throttled background queue.

Customized queues might be created by the person. Customized concurrent queues at all times mapped into one of many world queues by specifying a High quality of Service property (QoS). In many of the instances if you wish to run duties in parallel it’s endorsed to make use of one of many world concurrent queues, you must solely create customized serial queues.

System supplied queues

  • Serial major queue
  • Concurrent world queues
  • excessive precedence world queue
  • default precedence world queue
  • low precedence world queue
  • world background queue (io throttled)

Customized queues by high quality of service

  • userInteractive (UI updates) -> serial major queue
  • userInitiated (async UI associated duties) -> excessive precedence world queue
  • default -> default precedence world queue
  • utility -> low precedence world queue
  • background -> world background queue
  • unspecified (lowest) -> low precedence world queue

Sufficient from the idea, let’s have a look at the way to use the Dispatch framework in motion! 🎬


Find out how to use the DispatchQueue class in Swift?

Right here is how one can get all of the queues from above utilizing the model new GCD syntax obtainable from Swift 3. Please observe that you must at all times use a worldwide concurrent queue as a substitute of making your personal one, besides if you will use the concurrent queue for locking with limitations to realize thread security, extra on that later. 😳

Find out how to get a queue?

import Dispatch

DispatchQueue.major
DispatchQueue.world(qos: .userInitiated)
DispatchQueue.world(qos: .userInteractive)
DispatchQueue.world(qos: .background)
DispatchQueue.world(qos: .default)
DispatchQueue.world(qos: .utility)
DispatchQueue.world(qos: .unspecified)
DispatchQueue(label: "com.theswiftdev.queues.serial")
DispatchQueue(label: "com.theswiftdev.queues.concurrent", attributes: .concurrent)

So executing a job on a background queue and updating the UI on the primary queue after the duty completed is a fairly straightforward one utilizing Dispatch queues.

DispatchQueue.world(qos: .background).async {
    

    DispatchQueue.major.async {
        
    }
}

Sync and async calls on queues

There is no such thing as a large distinction between sync and async strategies on a queue. Sync is simply an async name with a semaphore (defined later) that waits for the return worth. A sync name will block, then again an async name will instantly return. 🎉

let q = DispatchQueue.world()

let textual content = q.sync {
    return "this may block"
}
print(textual content)

q.async {
    print("this may return immediately")
}

Principally in case you want a return worth use sync, however in each different case simply go together with async. DEADLOCK WARNING: you must by no means name sync on the primary queue, as a result of it will trigger a impasse and a crash. You need to use this snippet if you’re searching for a protected strategy to do sync calls on the primary queue / thread. 👌

Do not name sync on a serial queue from the serial queue’s thread!

Delay execution

You’ll be able to merely delay code execution utilizing the Dispatch framework.

DispatchQueue.major.asyncAfter(deadline: .now() + .seconds(2)) {
    
}

Carry out concurrent loop

Dispatch queue merely permits you to carry out iterations concurrently.

DispatchQueue.concurrentPerform(iterations: 5) { (i) in
    print(i)
}

Debugging

Oh, by the best way it is only for debugging goal, however you’ll be able to return the title of the present queue through the use of this little extension. Don’t use in manufacturing code!!!

extension DispatchQueue {
    static var currentLabel: String {
        return String(validatingUTF8: __dispatch_queue_get_label(nil))!
    }
}

Utilizing DispatchWorkItem in Swift

DispatchWorkItem encapsulates work that may be carried out. A piece merchandise might be dispatched onto a DispatchQueue and inside a DispatchGroup. A DispatchWorkItem can be set as a DispatchSource occasion, registration, or cancel handler.

So that you identical to with operations through the use of a piece merchandise you’ll be able to cancel a operating job. Additionally work objects can notify a queue when their job is accomplished.

var workItem: DispatchWorkItem?
workItem = DispatchWorkItem {
    for i in 1..<6 {
        guard let merchandise = workItem, !merchandise.isCancelled else {
            print("cancelled")
            break
        }
        sleep(1)
        print(String(i))
    }
}

workItem?.notify(queue: .major) {
    print("performed")
}

DispatchQueue.world().asyncAfter(deadline: .now() + .seconds(2)) {
    workItem?.cancel()
}
DispatchQueue.major.async(execute: workItem!)

Concurrent duties with DispatchGroups

So it is advisable to carry out a number of community calls with a view to assemble the information required by a view controller? That is the place DispatchGroup may help you. Your entire lengthy operating background job might be executed concurrently, when all the pieces is prepared you will obtain a notification. Simply watch out it’s a must to use thread-safe information constructions, so at all times modify arrays for instance on the identical thread! 😅

func load(delay: UInt32, completion: () -> Void) {
    sleep(delay)
    completion()
}

let group = DispatchGroup()

group.enter()
load(delay: 1) {
    print("1")
    group.depart()
}

group.enter()
load(delay: 2) {
    print("2")
    group.depart()
}

group.enter()
load(delay: 3) {
    print("3")
    group.depart()
}

group.notify(queue: .major) {
    print("performed")
}

Word that you simply at all times should steadiness out the enter and depart calls on the group. The dispatch group additionally permits us to trace the completion of various work objects, even when they run on totally different queues.

let group = DispatchGroup()
let queue = DispatchQueue(label: "com.theswiftdev.queues.serial")
let workItem = DispatchWorkItem {
    print("begin")
    sleep(1)
    print("finish")
}

queue.async(group: group) {
    print("group begin")
    sleep(2)
    print("group finish")
}
DispatchQueue.world().async(group: group, execute: workItem)



group.notify(queue: .major) {
    print("performed")
}

Yet one more factor that you need to use dispatch teams for: think about that you simply’re displaying a properly animated loading indicator when you do some precise work. It would occurs that the work is completed quicker than you’d anticipate and the indicator animation couldn’t end. To unravel this case you’ll be able to add a small delay job so the group will wait till each of the duties end. 😎

let queue = DispatchQueue.world()
let group = DispatchGroup()
let n = 9
for i in 0..<n {
    queue.async(group: group) {
        print("(i): Operating async job...")
        sleep(3)
        print("(i): Async job accomplished")
    }
}
group.wait()
print("performed")

Semaphores

A semaphore) is solely a variable used to deal with useful resource sharing in a concurrent system. It is a actually highly effective object, listed below are a number of necessary examples in Swift.

Find out how to make an async job to synchronous?

The reply is straightforward, you need to use a semaphore (bonus level for timeouts)!

enum DispatchError: Error {
    case timeout
}

func asyncMethod(completion: (String) -> Void) {
    sleep(2)
    completion("performed")
}

func syncMethod() throws -> String {

    let semaphore = DispatchSemaphore(worth: 0)
    let queue = DispatchQueue.world()

    var response: String?
    queue.async {
        asyncMethod { r in
            response = r
            semaphore.sign()
        }
    }
    semaphore.wait(timeout: .now() + 5)
    guard let consequence = response else {
        throw DispatchError.timeout
    }
    return consequence
}

let response = attempt? syncMethod()
print(response)

Lock / single entry to a useful resource

If you wish to keep away from race situation you’re in all probability going to make use of mutual exclusion. This might be achieved utilizing a semaphore object, but when your object wants heavy studying functionality you must contemplate a dispatch barrier primarily based answer. 😜

class LockedNumbers {

    let semaphore = DispatchSemaphore(worth: 1)
    var components: [Int] = []

    func append(_ num: Int) {
        self.semaphore.wait(timeout: DispatchTime.distantFuture)
        print("appended: (num)")
        self.components.append(num)
        self.semaphore.sign()
    }

    func removeLast() {
        self.semaphore.wait(timeout: DispatchTime.distantFuture)
        defer {
            self.semaphore.sign()
        }
        guard !self.components.isEmpty else {
            return
        }
        let num = self.components.removeLast()
        print("eliminated: (num)")
    }
}

let objects = LockedNumbers()
objects.append(1)
objects.append(2)
objects.append(5)
objects.append(3)
objects.removeLast()
objects.removeLast()
objects.append(3)
print(objects.components)

Look forward to a number of duties to finish

Identical to with dispatch teams, it’s also possible to use a semaphore object to get notified if a number of duties are completed. You simply have to attend for it…

let semaphore = DispatchSemaphore(worth: 0)
let queue = DispatchQueue.world()
let n = 9
for i in 0..<n {
    queue.async {
        print("run (i)")
        sleep(3)
        semaphore.sign()
    }
}
print("wait")
for i in 0..<n {
    semaphore.wait()
    print("accomplished (i)")
}
print("performed")

Batch execution utilizing a semaphore

You’ll be able to create a thread pool like conduct to simulate restricted assets utilizing a dispatch semaphore. So for instance if you wish to obtain plenty of photos from a server you’ll be able to run a batch of x each time. Fairly helpful. 🖐

print("begin")
let sem = DispatchSemaphore(worth: 5)
for i in 0..<10 {
    DispatchQueue.world().async {
        sem.wait()
        sleep(2)
        print(i)
        sem.sign()
    }
}
print("finish")

The DispatchSource object

A dispatch supply is a basic information kind that coordinates the processing of particular low-level system occasions.

Alerts, descriptors, processes, ports, timers and lots of extra. All the pieces is dealt with by way of the dispatch supply object. I actually do not need to get into the main points, it is fairly low-level stuff. You’ll be able to monitor information, ports, indicators with dispatch sources. Please simply learn the offical Apple docs. 📄

I might wish to make just one instance right here utilizing a dispatch supply timer.

let timer = DispatchSource.makeTimerSource()
timer.schedule(deadline: .now(), repeating: .seconds(1))
timer.setEventHandler {
    print("whats up")
}
timer.resume()

Thread-safety utilizing the dispatch framework

Thread security is an inevitable matter if it involves multi-threaded code. At first I discussed that there’s a thread pool below the hood of GCD. Each thread has a run loop object related to it, you’ll be able to even run them by hand. If you happen to create a thread manually a run loop can be added to that thread routinely.

let t = Thread {
    print(Thread.present.title ?? "")
     let timer = Timer(timeInterval: 1, repeats: true) { t in
         print("tick")
     }
     RunLoop.present.add(timer, forMode: .defaultRunLoopMode)

    RunLoop.present.run()
    RunLoop.present.run(mode: .commonModes, earlier than: Date.distantPast)
}
t.title = "my-thread"
t.begin()

You shouldn’t do that, demo functions solely, at all times use GCD queues!

Queue != Thread

A GCD queue will not be a thread, in case you run a number of async operations on a concurrent queue your code can run on any obtainable thread that matches the wants.

Thread security is all about avoiding tousled variable states

Think about a mutable array in Swift. It may be modified from any thread. That is not good, as a result of finally the values inside it are going to be tousled like hell if the array will not be thread protected. For instance a number of threads are attempting to insert values to the array. What occurs? In the event that they run in parallell which aspect goes to be added first? Now that is why you want generally to create thread protected assets.

Serial queues

You need to use a serial queue to implement mutual exclusivity. All of the duties on the queue will run serially (in a FIFO order), just one course of runs at a time and duties have to attend for one another. One large draw back of the answer is velocity. 🐌

let q = DispatchQueue(label: "com.theswiftdev.queues.serial")

q.async() {
  
}

q.sync() {
  
}

Concurrent queues utilizing limitations

You’ll be able to ship a barrier job to a queue in case you present an additional flag to the async methodology. If a job like this arrives to the queue it will make sure that nothing else can be executed till the barrier job have completed. To sum this up, barrier duties are sync (factors) duties for concurrent queues. Use async limitations for writes, sync blocks for reads. 😎

let q = DispatchQueue(label: "com.theswiftdev.queues.concurrent", attributes: .concurrent)

q.async(flags: .barrier) {
  
}

q.sync() {
  
}

This methodology will end in extraordinarily quick reads in a thread protected surroundings. You may also use serial queues, semaphores, locks all of it depends upon your present scenario, nevertheless it’s good to know all of the obtainable choices is not it? 🤐


A number of anti-patterns

It’s a must to be very cautious with deadlocks, race circumstances and the readers writers downside. Often calling the sync methodology on a serial queue will trigger you many of the troubles. One other challenge is thread security, however we have already coated that half. 😉

let queue = DispatchQueue(label: "com.theswiftdev.queues.serial")

queue.sync {
    
    queue.sync {
        
    }
}


DispatchQueue.world(qos: .utility).sync {
    
    DispatchQueue.major.sync {
        
    }
}

The Dispatch framework (aka. GCD) is a tremendous one, it has such a possible and it actually takes a while to grasp it. The true query is that what path goes to take Apple with a view to embrace concurrent programming into a complete new stage? Guarantees or await, perhaps one thing totally new, let’s hope that we’ll see one thing in Swift 6.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments