Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 146 ยท Concurrency

Threads and Dispatch

Learn Swift threads and Grand Central Dispatch - Thread, serial and concurrent DispatchQueue, DispatchGroup, semaphores, NSLock, and how they relate to async/await in Swift 6.

Before async and await existed, Swift programs (and Objective-C programs before them) did concurrent work with two tools: threads and Grand Central Dispatch, usually shortened to GCD or just Dispatch. You will still meet both. Foundation APIs take dispatch queues, older libraries hand you completion handlers that fire on some queue, and plenty of production code predates Swift concurrency.

This lesson teaches you to read and write that code safely. You will start a Thread, use serial and concurrent DispatchQueues, wait for a batch of jobs with DispatchGroup, guard shared state with a lock, see the exact Swift 6 compile errors for unsafe code, and learn how to bridge Dispatch into async/await. For new code you should prefer tasks and actors, but you cannot do that well until you understand what sits underneath.

Threads: the lowest level

A thread is a path of execution inside your process. Your program always starts with one, the main thread. The operating system can run several threads at the same time (if the machine has several cores) or take turns between them (if it does not). All threads of a process share the same memory, which is both the power and the danger.

Foundation's Thread class wraps an operating-system thread. You give it a closure and call start(). The closure runs on the new thread while your main thread carries on.

Swift Starting a Thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The worker prints false for Thread.isMainThread, the main thread prints true. The DispatchSemaphore is the simplest way to say "wait until the other side has signalled". A semaphore holds a counter: wait() blocks while the counter is zero, and signal() adds one. Starting at 0 means wait() blocks until the worker calls signal().

Notice what is not in the example: any promise about order. The line main: waiting for the worker can appear before or after the worker's first line, because the two threads are independent. That is the first rule of threads: without synchronization, you get no ordering.

Threads have real costs. Each one reserves a stack (often 512 KB to 8 MB of address space), the operating system must schedule it, and creating hundreds of them is slow. Modern Swift code almost never creates a Thread by hand. You will see it mostly for long-lived background loops in older code, or when a C library demands a dedicated thread.

On Linux, the sandbox used by this site reports the same name for every thread whatever you set in thread.name, so the examples here never print thread names. Use Thread.isMainThread when you need to know where code runs.

Dispatch queues: describe the work, not the thread

Grand Central Dispatch turns the question around. Instead of creating threads, you hand blocks of work to a queue, and the system runs them on a pool of threads that it manages for you. You never create or destroy a thread. A DispatchQueue comes in two shapes.

  • A serial queue runs one block at a time, in the order you submitted them. It is the default.
  • A concurrent queue starts blocks in order but lets several run at once, so they may finish in any order.

You submit work in one of two ways. async returns immediately and the block runs later. sync blocks the caller until the block has finished, and can return a value.

Swift A serial queue keeps order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Because the queue is serial, the output is always job 1, job 2, job 3, sync block, answer: 42. A sync call on a serial queue is therefore also a handy way to say "wait until everything I queued earlier has finished". The label is only a name for debuggers and crash reports, but give every queue a reverse-DNS-style one anyway.

You will also see quality of service (QoS) classes: .userInteractive, .userInitiated, .utility and .background. They tell the system how urgent the work is. DispatchQueue.global(qos: .utility) returns one of the system's shared concurrent queues. Use the global queues for fire-and-forget work, and your own labelled queues when you need to protect a piece of state.

Dispatch and Swift 6: data races are compile errors

The classic bug with threads is the data race: two threads touch the same variable at once and at least one of them writes. Increments like total += 1 are really "read, add, write", so two threads can both read 5 and both write 6, losing an update. In older Swift this compiled and failed at random. In Swift 6 language mode the compiler refuses.

Swift A data race on a global variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with:

TEXT
main.swift:8:29: error: main actor-isolated var 'total' can not be mutated from a nonisolated context

In a main.swift file, top-level variables belong to the main actor, so touching them from a background queue is rejected. The same protection applies to a local variable captured by a closure that runs concurrently:

Swift Mutating a captured local (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

TEXT
main.swift:6:19: error: mutation of captured var 'sum' in concurrently-executing code [#SendableClosureCaptures]

The block you pass to async is a @Sendable closure, which means it may run on another thread at any time, so it must not capture a mutable variable. The cure is to put the state inside a type that guards itself with a lock.

Locks: protecting shared state

An NSLock lets only one thread past lock() at a time until it calls unlock(). Wrap the lock and the data together in a small class so that nothing can reach the data without taking the lock.

Swift A counter protected by NSLock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program always prints total: 4000. Four blocks run on a concurrent queue, but every increment takes the lock first. Three details deserve attention:

  1. defer { lock.unlock() } guarantees the unlock even if the function returns early or throws. Forgetting to unlock is a deadlock waiting to happen.
  2. The class is marked @unchecked Sendable. You are telling the compiler "I have made this type thread-safe myself, trust me". The word unchecked is honest: if you later add a property that is not guarded by the lock, the compiler will not warn you. Keep every access to mutable state behind the lock.
  3. The getter locks too. Reading while another thread writes is also a race.

Locks are fast, but they do not compose well. Holding one lock while taking another invites deadlocks, and nothing stops a teammate from reading value without the lock. The next lesson, Synchronization and Shared State, shows the Mutex type from the standard library, which makes "forgetting the lock" impossible, and compares it with actors.

DispatchGroup: wait for a batch

When you start many jobs and need to know when they are all done, use a DispatchGroup. Pass it to async(group:), or call enter() before starting work and leave() when it ends (the manual form is perfect for callback-based APIs). wait() blocks until the group is empty, and wait(timeout:) gives up after a deadline.

Swift DispatchGroup with enter, leave and a timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first group finishes and prints all three entries (sorted, because the jobs finish in any order). The second group shows the classic bug in manual use: every enter() needs exactly one leave(). With no leave(), a plain wait() would hang forever, so prefer wait(timeout:) or group.notify(queue:execute:), which runs a block when the group empties instead of blocking a thread.

concurrentPerform: parallel loops

DispatchQueue.concurrentPerform(iterations:execute:) runs a loop body in parallel across the available cores and returns when every iteration is done. It chooses the number of threads for you, so it is the right tool for CPU-heavy loops where each iteration is independent.

Swift A parallel loop with concurrentPerform

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each iteration writes only its own slot, so the result is always [0, 1, 4, 9, 16, 25] even though the order of the iterations is up to the system. On a machine with one core, as in this sandbox, concurrentPerform simply runs the iterations one after another, which is why you should never count on a speedup for tiny loop bodies. Make the body do enough work to outweigh the cost of scheduling.

Deadlocks and other traps

A deadlock happens when code waits for something that can only happen after the waiting is over. With queues, the textbook case is calling sync on a serial queue from code that is already running on that queue. The inner block cannot start until the outer block finishes, and the outer block cannot finish until the inner one does.

Swift Calling sync on the queue you are on (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

libdispatch detects this particular mistake and kills the program. The output shows outer and then a crash with the signal SIGILL and a backtrace that mentions __DISPATCH_WAIT_FOR_QUEUE__. There is no friendly message, only the name of that function in the backtrace. Other deadlocks are not detected at all: the program just hangs.

Habits that avoid trouble:

  • Never call sync on a queue from code that may already be running on it.
  • Do not block the main thread while it is needed to deliver results.
  • Keep work inside a lock short. Never call unknown code, such as a user-supplied closure, while holding one.
  • When several locks are needed, always take them in the same order.
  • Do not create a thread (or a blocked queue block) per item. Thread explosion exhausts memory.

How Dispatch relates to Swift concurrency

Swift concurrency (async, tasks, actors) runs on top of the same ideas, but it hides the threads. A task is not a thread. It is a unit of work that the runtime schedules onto a small pool of threads, and when it reaches an await it gives its thread back instead of blocking it. That is why thousands of tasks are fine, while thousands of blocked threads are not. Never mix the two carelessly: calling group.wait() or semaphore.wait() inside an async function blocks one of the few pool threads and can starve other tasks.

When you meet an old API that reports completion through a block, wrap it so callers can use await. A continuation is the bridge: you start the old-style work, and call resume when it delivers.

Swift Bridging a Dispatch callback to async

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Exactly one resume per continuation is the rule; Bridging Callbacks to async covers the details and the runtime checks that enforce it.

When should you still pick Dispatch in new code? Rarely: a dedicated serial queue to serialize access to a legacy non-Sendable object, concurrentPerform for a data-parallel number-crunching loop, or an API that insists on a DispatchQueue parameter. And on the main queue, avoid DispatchQueue.main.async in new code. Use @MainActor isolation instead, as described in Actors.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a serial DispatchQueue guarantee?

    A serial queue runs a single block at a time in first-in, first-out order. A concurrent queue is the one that allows several blocks to run at once.
  2. 2. Why does Swift 6 reject queue.async { sum += 1 } when sum is a local var?

    The compiler reports 'mutation of captured var in concurrently-executing code'. Move the state into a type that protects itself with a lock, an actor, or a Mutex.
  3. 3. What is the purpose of group.enter() and group.leave()?

    Each enter() must be balanced by exactly one leave(). The group is empty, and wait() or notify() fires, only when the counts match.
  4. 4. What happens when you call queue.sync { } from inside a block already running on the same serial queue?

    The inner block waits for the outer one to finish while the outer waits for the inner. libdispatch notices this particular case and terminates the program with SIGILL.
  5. 5. Why should you avoid semaphore.wait() inside an async function?

    A task that blocks a thread cannot give it back at an await, so a few blocked tasks can stall everything. Use await-based tools or continuations instead.

Summary

  • A Thread is an operating-system thread. It is heavy, gives no ordering guarantees, and is rarely created by hand in modern Swift.
  • A DispatchQueue accepts blocks of work. Serial queues run them one at a time in order; concurrent queues run several at once. async returns immediately, sync waits.
  • In Swift 6, mutating a global or a captured local from a @Sendable closure is a compile error (main actor-isolated var ... can not be mutated from a nonisolated context, mutation of captured var ... in concurrently-executing code).
  • Protect shared state with a lock inside a class marked @unchecked Sendable, and use defer to unlock.
  • DispatchGroup waits for a batch of jobs; every enter() needs one leave(), and wait(timeout:) or notify avoids hanging forever.
  • concurrentPerform runs independent iterations in parallel.
  • sync on the queue you are already on deadlocks. Blocking calls inside async code starve the task pool.
  • Bridge callback-style Dispatch code with withCheckedContinuation; prefer tasks and actors for new code.

Next: Synchronization and Shared State shows the standard library's Mutex and Atomic types and when to choose them over actors.