Structured concurrency with async let and TaskGroup

suggest change

async/await (Swift 5.5) lets a function suspend while it waits. By default, though, await runs things one after another. To run work in parallel, Swift has two structured concurrency tools:

"Structured" means each child task belongs to the scope that created it. The scope can't return until all its children have finished. Errors flow from children up to the parent, and cancelling the parent cancels every child. So you can't leak a task that keeps running after the function that started it has returned. This is the big difference from DispatchQueue.async (see Running tasks in a Grand Central Dispatch GCD queue) and from unstructured Task { }.

All examples are complete programs, compiled with Swift 6.4.1 in Swift 6 language mode:

swiftc -swift-version 6 -parse-as-library main.swift

async let: a fixed number of parallel jobs

Write async let instead of let and the right-hand side starts right away as a child task. The current function keeps going. You await the value later, at the point where you need it:

func fetchUser(id: Int) async -> String {
    try? await Task.sleep(for: .milliseconds(300))
    return "user\(id)"
}

func fetchOrders(userID: Int) async -> [String] {
    try? await Task.sleep(for: .milliseconds(500))
    return ["book", "lamp"]
}

// rounds to the nearest 100 ms so the output is stable
func approx(_ d: Duration) -> String {
    let ms = Int(d / .milliseconds(1))
    return "\((ms + 50) / 100 * 100) ms"
}

@main
struct App {
    static func main() async {
        let clock = ContinuousClock()

        let sequential = await clock.measure {
            let user = await fetchUser(id: 1)
            let orders = await fetchOrders(userID: 1)
            print("sequential:", user, orders)
        }

        let parallel = await clock.measure {
            async let user = fetchUser(id: 1)
            async let orders = fetchOrders(userID: 1)
            // both child tasks are already running here
            print("parallel:", await user, await orders)
        }

        print("sequential took about \(approx(sequential))")
        print("parallel took about \(approx(parallel))")
    }
}

Output:

sequential: user1 ["book", "lamp"]
parallel: user1 ["book", "lamp"]
sequential took about 800 ms
parallel took about 500 ms

With plain let the two calls run one after the other (300 + 500 ms). With async let they overlap, so the total is the slower of the two.

Some rules:

Errors with async let

If the child task throws, you get the error when you try await its value. When the scope exits with an error, Swift cancels every child that is still running and waits for it before it propagates the error:

struct NotFound: Error {}

func loadProfile(id: Int) async throws -> String {
    try await Task.sleep(for: .milliseconds(100))
    if id == 0 { throw NotFound() }
    return "profile\(id)"
}

func loadAvatar(id: Int) async throws -> String {
    do {
        try await Task.sleep(for: .seconds(2))
    } catch {
        print("avatar \(id): cancelled")
        throw error
    }
    return "avatar\(id).png"
}

func loadPage(id: Int) async throws -> String {
    async let profile = loadProfile(id: id)
    async let avatar = loadAvatar(id: id)
    // try is needed because the child task can throw
    return try await "\(profile) + \(avatar)"
}

@main
struct App {
    static func main() async {
        let clock = ContinuousClock()
        let start = clock.now
        do {
            print(try await loadPage(id: 0))
        } catch {
            let elapsed = clock.now - start
            print("failed with \(error), elapsed < 1s: \(elapsed < .seconds(1))")
        }
    }
}

Output:

avatar 0: cancelled
failed with NotFound(), elapsed < 1s: true

loadProfile fails after 100 ms. The error leaves loadPage, so avatar gets cancelled. Task.sleep notices the cancellation and throws CancellationError, and we don't wait the full 2 seconds.

One detail: try await "\(profile) + \(avatar)" reads profile first. If avatar failed first, the error would only show up after profile finished. Swift doesn't race the bindings against each other. When you want "fail as soon as any child fails", use a throwing task group (shown below).

Unused async let is cancelled, not leaked

If you never await an async let, Swift doesn't silently let it run on. At the end of the scope it cancels the child and then waits for it:

func slowWork(_ name: String) async -> Int {
    do {
        try await Task.sleep(for: .seconds(1))
        print("\(name) finished")
    } catch {
        print("\(name) was cancelled")
    }
    return 42
}

func run(useResult: Bool) async {
    async let a = slowWork("a")
    async let b = slowWork("b")
    if useResult {
        print("sum:", await a + b)
    }
    // b and a are cancelled and awaited here if never awaited
}

@main
struct App {
    static func main() async {
        await run(useResult: false)
        print("---")
        await run(useResult: true)
    }
}

Output:

b was cancelled
a was cancelled
---
a finished
b finished
sum: 84

The order of the "cancelled" lines can vary between runs. So async let is not fire-and-forget. If you want work to keep running after the function returns, that's an unstructured Task, covered in Tasks and cancellation.

withTaskGroup: a dynamic number of jobs

async let needs one binding per job, so it doesn't work for "download every file in this list". For that, use a task group:

func download(_ name: String, ms: Int) async -> Int {
    try? await Task.sleep(for: .milliseconds(ms))
    return name.count * 100
}

@main
struct App {
    static func main() async {
        let files = ["a.txt": 300, "bb.txt": 100, "ccc.txt": 200]

        let total = await withTaskGroup(of: (String, Int).self) { group in
            for (name, ms) in files {
                group.addTask {
                    (name, await download(name, ms: ms))
                }
            }

            var sum = 0
            // results arrive in completion order, not in the order added
            for await (name, size) in group {
                print("\(name): \(size) bytes")
                sum += size
            }
            return sum
        }
        print("total:", total)
    }
}

Output:

bb.txt: 600 bytes
ccc.txt: 700 bytes
a.txt: 500 bytes
total: 1800

How it works:

Keeping results in input order

Since results arrive in completion order, return the index along with the value and put each result in its slot:

func square(_ n: Int) async -> Int {
    // later items finish first
    try? await Task.sleep(for: .milliseconds(100 * (5 - n)))
    return n * n
}

@main
struct App {
    static func main() async {
        let inputs = [1, 2, 3, 4]

        // Swift 6.1+: the child result type is inferred from addTask
        let squares = await withTaskGroup { group in
            for (i, n) in inputs.enumerated() {
                group.addTask { (i, await square(n)) }
            }
            var results = [Int](repeating: 0, count: inputs.count)
            for await (i, value) in group {
                print("finished index \(i)")
                results[i] = value
            }
            return results
        }
        print(squares)
    }
}

Output:

finished index 3
finished index 2
finished index 1
finished index 0
[1, 4, 9, 16]

This example also uses a Swift 6.1 change. withTaskGroup and withThrowingTaskGroup no longer need the of: argument, because the child result type is inferred from the addTask closures. On Swift 5.5 - 6.0 you have to write withTaskGroup(of: (Int, Int).self) { ... }. Writing of: still works and is often clearer, especially when the closure is long.

A [Int: Value] dictionary also works when the input isn't indexed.

next(), isEmpty and waitForAll()

Besides for await, a group gives you more control:

func work(_ n: Int) async -> Int {
    try? await Task.sleep(for: .milliseconds(100 * n))
    return n
}

@main
struct App {
    static func main() async {
        // next(): pull one result at a time
        await withTaskGroup(of: Int.self) { group in
            for n in [3, 1, 2] { group.addTask { await work(n) } }
            while let first = await group.next() {
                print("got", first)
            }
            print("isEmpty:", group.isEmpty)
        }

        // waitForAll(): children only have side effects
        await withTaskGroup(of: Void.self) { group in
            for n in 1...3 {
                group.addTask { print("side effect", await work(n)) }
            }
            await group.waitForAll()
            print("all done")
        }
    }
}

Output:

got 1
got 2
got 3
isEmpty: true
side effect 1
side effect 2
side effect 3
all done

Since the group is an AsyncSequence, you might try await group.reduce(0, +). In Swift 6 mode, inside a main-actor-isolated function such as main(), this fails to compile with sending 'group' risks causing data races. A for await loop that adds up the values compiles fine.

withThrowingTaskGroup: errors and cancellation

When children can throw, use withThrowingTaskGroup. Its addTask closure can throw, and for try await / try await group.next() rethrow the first error they meet:

struct BadInput: Error { let value: Int }

func parse(_ n: Int) async throws -> Int {
    do {
        try await Task.sleep(for: .milliseconds(100 * n))
    } catch {
        print("  child \(n) cancelled")
        throw error
    }
    if n == 2 { throw BadInput(value: n) }
    print("  child \(n) ok")
    return n * 10
}

@main
struct App {
    static func main() async {
        do {
            let values = try await withThrowingTaskGroup(of: Int.self) { group in
                for n in 1...5 {
                    group.addTask { try await parse(n) }
                }
                var all: [Int] = []
                // rethrows the first child error; leaving the closure
                // with an error cancels the remaining children
                for try await v in group {
                    all.append(v)
                }
                return all
            }
            print(values)
        } catch {
            print("group failed: \(error)")
        }
    }
}

Output:

  child 1 ok
  child 3 cancelled
  child 4 cancelled
  child 5 cancelled
group failed: BadInput(value: 2)

Here is what happened:

  1. Child 1 finished after 100 ms. Child 2 threw BadInput after 200 ms.
  2. for try await rethrew the error, so the closure exits with that error.
  3. A group that exits with an error cancels all remaining children and waits for them before the error leaves withThrowingTaskGroup. Children 3, 4 and 5 were still sleeping, so Task.sleep threw CancellationError in each of them.

Two important points:

Checking for cancellation in children

Cancelling the parent task cancels the group and all its children. A long-running child should check Task.isCancelled (or call try Task.checkCancellation()) and stop early:

func crunch(_ n: Int) async -> Int {
    var sum = 0
    for i in 0..<5 {
        // cancellation is cooperative: check it yourself
        if Task.isCancelled {
            print("  job \(n) stops at step \(i)")
            return sum
        }
        sum += i
        try? await Task.sleep(for: .milliseconds(100))
    }
    print("  job \(n) completed")
    return sum
}

@main
struct App {
    static func main() async {
        let outer = Task {
            await withTaskGroup(of: Int.self) { group in
                for n in 1...3 {
                    group.addTask { await crunch(n) }
                }
                await group.waitForAll()
                // the group is cancelled, so this child is never started
                let added = group.addTaskUnlessCancelled { await crunch(99) }
                print("added job 99: \(added)")
            }
        }
        try? await Task.sleep(for: .milliseconds(250))
        outer.cancel() // cancelling the parent cancels every child
        await outer.value
    }
}

Output (the job order varies):

  job 2 stops at step 3
  job 3 stops at step 3
  job 1 stops at step 3
added job 99: false

After 250 ms the outer task is cancelled. Each job's Task.sleep returns early (we ignore its error with try?), the next loop iteration sees Task.isCancelled == true, and the job returns a partial result. addTaskUnlessCancelled starts a child only if the group isn't cancelled, and returns false otherwise. It's useful in loops that add work over a long time. You can also cancel a group yourself with group.cancelAll().

Unstructured Task, withTaskCancellationHandler and other cancellation APIs are covered in Tasks and cancellation.

Limiting how many tasks run at once

addTask starts the child right away. Adding 10,000 children means 10,000 tasks at once. The runtime runs them on a thread pool about the size of your CPU core count, so you won't get 10,000 threads. But you may still open 10,000 network connections or hold 10,000 images in memory. To limit this, start N tasks, then add a new one each time one finishes:

func resize(_ image: Int) async -> String {
    try? await Task.sleep(for: .milliseconds(100))
    return "img\(image)"
}

actor Counter {
    var running = 0, peak = 0
    func enter() { running += 1; peak = max(peak, running) }
    func leave() { running -= 1 }
}

@main
struct App {
    static func main() async {
        let images = Array(1...10)
        let maxConcurrent = 3
        let counter = Counter()

        let done = await withTaskGroup(of: String.self) { group in
            func add(_ image: Int) {
                group.addTask {
                    await counter.enter()
                    let r = await resize(image)
                    await counter.leave()
                    return r
                }
            }

            var iterator = images.makeIterator()
            // start the first batch
            for _ in 0..<maxConcurrent {
                if let image = iterator.next() { add(image) }
            }
            var results: [String] = []
            // each time one finishes, start the next one
            while let r = await group.next() {
                results.append(r)
                if let image = iterator.next() { add(image) }
            }
            return results
        }
        print("processed \(done.count) images, peak concurrency: \(await counter.peak)")
    }
}

Output:

processed 10 images, peak concurrency: 3

The Counter actor just records how many children were running at the same time. The pattern is the while let r = await group.next() loop. Every finished child makes room for one new child, so at most maxConcurrent are ever running.

First result wins: timeouts and racing

group.next() followed by group.cancelAll() gives you "use whichever child finishes first, cancel the rest". That's how you build a timeout:

struct TimeoutError: Error {}

func withTimeout<T: Sendable>(
    _ limit: Duration,
    _ operation: @escaping @Sendable () async throws -> T
) async throws -> T {
    try await withThrowingTaskGroup(of: T.self) { group in
        group.addTask { try await operation() }
        group.addTask {
            try await Task.sleep(for: limit)
            throw TimeoutError()
        }
        // whichever child finishes first decides the result
        let result = try await group.next()!
        group.cancelAll()
        return result
    }
}

func query(_ ms: Int) async throws -> String {
    try await Task.sleep(for: .milliseconds(ms))
    return "answer after \(ms) ms"
}

@main
struct App {
    static func main() async {
        for ms in [100, 2000] {
            do {
                print(try await withTimeout(.milliseconds(500)) { try await query(ms) })
            } catch {
                print("query(\(ms)) failed: \(error)")
            }
        }

        // first mirror to answer wins
        let fastest = await withTaskGroup(of: String.self) { group in
            for (mirror, ms) in [("eu", 300), ("us", 100), ("asia", 200)] {
                group.addTask {
                    try? await Task.sleep(for: .milliseconds(ms))
                    return mirror
                }
            }
            let first = await group.next()!
            group.cancelAll()
            return first
        }
        print("fastest mirror:", fastest)
    }
}

Output:

answer after 100 ms
query(2000) failed: TimeoutError()
fastest mirror: us

In withTimeout, two children race. One runs the operation and the other sleeps, then throws TimeoutError. The first to finish decides the result, and cancelAll() stops the loser. The group still waits for the cancelled child before it returns. That's why Task.sleep, which reacts to cancellation right away, is the right tool here. An operation that ignores cancellation would delay the return even after the timeout.

withDiscardingTaskGroup for fire-and-forget children

Swift 5.9 added withDiscardingTaskGroup and withThrowingDiscardingTaskGroup. Children return Void, and each child is cleaned up as soon as it finishes, without waiting for you to call next(). This is meant for long-lived groups like a server accept loop, where a normal group would keep collecting finished results in memory:

actor Log {
    var lines: [String] = []
    func add(_ s: String) { lines.append(s) }
}

@main
struct App {
    static func main() async {
        let log = Log()
        // children return Void and their results are discarded right away,
        // so memory does not grow for long-running groups
        await withDiscardingTaskGroup { group in
            for n in 1...4 {
                group.addTask {
                    try? await Task.sleep(for: .milliseconds(100 * n))
                    await log.add("handled request \(n)")
                }
            }
        }
        for line in await log.lines { print(line) }
    }
}

Output:

handled request 2
handled request 1
handled request 3
handled request 4

A discarding group has no next() and no for await. In the throwing variant, the first error a child throws cancels the whole group, and withThrowingDiscardingTaskGroup rethrows it.

async let vs task groups vs concurrentPerform

async let withTaskGroup DispatchQueue.concurrentPerform
Number of jobs fixed at compile time dynamic dynamic
Result types can differ per binding one type for all children none (closure returns Void)
Blocks the calling thread no (suspends) no (suspends) yes
Error propagation try await on the value first error read, rest cancelled manual
Cancellation automatic when scope exits automatic + cancelAll() none

Use async let for "load these 2-3 different things at the same time". Use a task group for "do this for every item in a collection". Concurrent Loops with concurrentPerform still makes sense for CPU-bound synchronous code that isn't async.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents