Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

Concurrency with async and await

Waiting without blocking: async functions, running work side by side with async let and task groups, cancellation, actors that prevent data races, and asynchronous sequences.

CS61A
Browsers · Applications
Swift book
Concurrency

Most of the time a real program spends is spent waiting: for a web server to answer, for a file to arrive from disk, for a person to click. CS61A’s lectures on browsers and applications look at programs that live among other programs and machines. A program that does nothing while it waits for one thing is wasting all the time it could spend on others.

Swift’s answer is built into the language: async functions that can pause while they wait, await to mark where they might pause, and a system of tasks that lets many pieces of work be in progress at once.

Concurrency and parallelism

Two words are easy to confuse:

  • Concurrency is having several tasks in progress at the same time. A cook with three pots on the stove works concurrently: while one pot heats, they chop for another.
  • Parallelism is several things executing at the same instant, which needs several processors, or several cooks.

Swift’s concurrency is mostly about the first: structuring a program so that waiting in one place does not stop progress elsewhere. The runtime then uses parallelism, running tasks on several cores, when it can.

async and await

A function marked async can suspend: pause partway through, give its thread to other work, and resume later. Every call to an async function is marked with await, which shows where that might happen:

func fetchScore(for player: String) async -> Int {
    // Pretend this is a network request that takes 0.1 seconds.
    try? await Task.sleep(for: .milliseconds(100))
    return player.count * 10
}

let score = await fetchScore(for: "Ada")
print(score)   // 30

Task.sleep stands in for a slow operation throughout this lesson. Unlike a busy loop, it does not occupy a processor while it waits: the task suspends, and whatever else is ready runs instead. It throws if the task is cancelled (more on that below), and try? ignores that here.

The rules mirror throws and try:

  • Only async code can call async functions. The top level of a script counts as async code, which is why await works above.
  • await marks every possible suspension point, the way try marks every possible early exit. Between two awaits, code runs without interruption.
  • A function can be both: async throws, called with try await.

Doing several things at once

awaiting one call after another is still sequential. This takes about 0.3 seconds, the sum of three waits:

func fetchScore(for player: String) async -> Int {
    try? await Task.sleep(for: .milliseconds(100))
    return player.count * 10
}

let clock = ContinuousClock()
let start = clock.now
let a = await fetchScore(for: "Ada")
let b = await fetchScore(for: "Alan")
let c = await fetchScore(for: "Grace")
let elapsed = clock.now - start
print(a + b + c, elapsed >= .milliseconds(300))   // 120 true

The three requests do not depend on each other, so there is no reason to wait for one before starting the next. async let starts a call immediately, as a child task, and lets the current code continue; the await comes when the value is needed:

func fetchScore(for player: String) async -> Int {
    try? await Task.sleep(for: .milliseconds(100))
    return player.count * 10
}

let clock = ContinuousClock()
let start = clock.now
async let a = fetchScore(for: "Ada")
async let b = fetchScore(for: "Alan")
async let c = fetchScore(for: "Grace")
let total = await a + b + c
let elapsed = clock.now - start
print(total, elapsed < .milliseconds(250))   // 120 true

All three waits overlap, so the whole thing takes about 0.1 seconds instead of 0.3. The answer is the same; only the waiting changed.

What would Swift print?

func double(_ n: Int) async -> Int {
    try? await Task.sleep(for: .milliseconds(10 * n))
    return n * 2
}
async let x = double(3)
async let y = double(1)
let results = await [x, y]
print(results)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer[6, 2]

y finishes first, since it sleeps less, but [x, y] lists the results in the order they are written. Awaiting an async let waits for that value, whenever it arrives.

Task groups

async let needs one line per task, so it only works when you know how many tasks there are while writing the code. For a number known only at run time, use a task group:

func fetchScore(for player: String) async -> Int {
    try? await Task.sleep(for: .milliseconds(100))
    return player.count * 10
}

let players = ["Ada", "Alan", "Grace", "Barbara", "Edsger"]

let scores = await withTaskGroup(of: (String, Int).self) { group in
    for player in players {
        group.addTask {
            (player, await fetchScore(for: player))
        }
    }
    var scores: [String: Int] = [:]
    for await (player, score) in group {
        scores[player] = score
    }
    return scores
}

print(scores["Grace"]!, scores.count)   // 50 5

addTask starts one child task per player, all running concurrently. for await … in group receives the results in the order they finish, which is not necessarily the order they were added. That is why each task returns its player’s name along with the score: the results are gathered into a dictionary, and the order stops mattering.

The group waits for all of its child tasks before withTaskGroup returns. This is structured concurrency: tasks are created inside a scope and cannot outlive it, so, like a local variable, a task never leaks past the code that started it. async let is structured the same way.

For tasks that can throw, withThrowingTaskGroup works the same way, and the first error thrown out of the group cancels the remaining tasks.

What would Swift print?

let total = await withTaskGroup(of: Int.self) { group in
    for n in 1...4 {
        group.addTask { n * n }
    }
    var sum = 0
    for await square in group {
        sum += square
    }
    return sum
}
print(total)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer30

1 + 4 + 9 + 16 is 30, whatever order the squares arrive in. Adding up is a good fit for a task group because the order does not matter.

Cancellation

A task can be cancelled, for example when a user closes the screen that needed its result. Cancellation in Swift is cooperative: it does not stop a task by force, it sets a flag, and the task is expected to notice and stop.

  • Task.isCancelled is true once the current task has been cancelled.
  • try Task.checkCancellation() throws a CancellationError if it has.
  • Task.sleep and many other waiting functions throw CancellationError immediately when cancelled.

Task { … } creates an unstructured task, one that is not tied to a scope, and returns a handle you can cancel() or await the value of:

let task = Task {
    var completed = 0
    for _ in 1...10 {
        do {
            try await Task.sleep(for: .milliseconds(50))
        } catch {
            break   // cancelled
        }
        completed += 1
    }
    return completed
}

try? await Task.sleep(for: .milliseconds(120))
task.cancel()
let completed = await task.value
print(completed < 10)   // true

The task got through two or three steps before it was cancelled, and then stopped, instead of spending another 0.4 seconds on work nobody needed.

Data races and actors

Tasks run concurrently, possibly in parallel, so two of them may touch the same data at the same moment. If at least one is writing, that is a data race, and the result is unpredictable: two tasks that each add 1 to a counter can both read 5, both write 6, and one increment is lost.

Swift 6 prevents data races at compile time. Values passed between tasks must be Sendable, safe to share: value types made of Sendable parts, like Int, String, and arrays of them, qualify automatically, because each task gets its own copy (Lesson 13). Shared mutable state must be protected by an actor.

An actor is like a class whose state can only be touched by one task at a time. Code outside the actor must await to use it, because it may have to wait its turn:

actor Counter {
    private(set) var value = 0

    func increment() {
        value += 1
    }
}

let counter = Counter()
await withTaskGroup(of: Void.self) { group in
    for _ in 1...1000 {
        group.addTask {
            await counter.increment()
        }
    }
}
print(await counter.value)   // 1000

A thousand tasks increment concurrently, and not one increment is lost. Inside the actor, increment reads and writes value without any await: code running on the actor has exclusive access, so the read and the write cannot be interleaved with another task’s.

The compiler enforces the boundary. Changing an actor’s state directly from outside is an error, not a race waiting to happen:

actor Counter {
    var value = 0
}

let counter = Counter()
counter.value += 1

The main actor

Apps have one special actor, the main actor, which owns the user interface. Code that updates the screen is marked @MainActor, and slow work runs elsewhere, returning to the main actor only to show its results. That is how an app stays responsive while it downloads: the waiting happens off the main actor.

Asynchronous sequences

Some results arrive over time: lines of a file as it downloads, messages in a chat, ticks of a timer. An asynchronous sequence is Lesson 17’s Sequence, except that getting the next element may need to wait. You loop over one with for await:

func countdown(from start: Int) -> AsyncStream<Int> {
    AsyncStream { continuation in
        Task {
            for n in stride(from: start, through: 1, by: -1) {
                continuation.yield(n)
                try? await Task.sleep(for: .milliseconds(20))
            }
            continuation.finish()
        }
    }
}

for await n in countdown(from: 3) {
    print(n)
}
print("liftoff")
// 3
// 2
// 1
// liftoff

AsyncStream builds a sequence from a closure: yield sends the next element to whoever is looping, and finish ends the loop. The consumer’s for await suspends between elements instead of blocking. Many standard functions have asynchronous versions of the sequence methods you know, such as prefix, map, and filter.

Put the lines in order

Put the lines in order so the program prints 12.

  1. }
  2. let b = await triple(a)
  3. async let a = triple(1)
  4. print(b + 3)
  5. n * 3
  6. func triple(_ n: Int) async -> Int {

Show the correct program
func triple(_ n: Int) async -> Int {
    n * 3
}
async let a = triple(1)
let b = await triple(a)
print(b + 3)

Lab 21: Concurrency

The problems simulate slow work with Task.sleep. Timing assertions allow a generous margin, since a busy computer can make sleeps run late, never early.

Q0: What would Swift print?

What would Swift print?

actor Tally {
    var total = 0
    func add(_ n: Int) {
        total += n
    }
}
let tally = Tally()
await withTaskGroup(of: Void.self) { group in
    for n in 1...10 {
        group.addTask { await tally.add(n) }
    }
}
print(await tally.total)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer55

The ten additions happen in some unpredictable order, but the actor runs them one at a time and addition does not care about order: 1 + 2 + … + 10 = 55.

What would Swift print?

func slow(_ label: String, _ ms: Int) async -> String {
    try? await Task.sleep(for: .milliseconds(ms))
    return label
}
let first = await withTaskGroup(of: String.self) { group in
    group.addTask { await slow("tortoise", 300) }
    group.addTask { await slow("hare", 10) }
    let winner = await group.next()!
    group.cancelAll()
    return winner
}
print(first)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answerhare

group.next() returns the first result to finish, and the hare’s task finishes first even though it was added second. cancelAll() then cancels the tortoise, whose Task.sleep stops early.

Q1: Download everything

Write downloadAll(_:), which “downloads” every page concurrently using the provided download(_:) and returns a dictionary from each name to its size. Five downloads of 0.1 seconds each should take about 0.1 seconds in total, not 0.5.

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

func downloadAll(_ pages: [String]) async -> [String: Int] {
    await withTaskGroup(of: (String, Int).self) { group in
        for page in pages {
            group.addTask { (page, await download(page)) }
        }
        var sizes: [String: Int] = [:]
        for await (page, size) in group {
            sizes[page] = size
        }
        return sizes
    }
}

let clock = ContinuousClock()
let start = clock.now
let sizes = await downloadAll(["home", "about", "blog", "swift", "cs61a"])
assert(sizes == ["home": 400, "about": 500, "blog": 400, "swift": 500, "cs61a": 500])
assert(clock.now - start < .milliseconds(400))

Q2: Keep the order

A task group returns results in the order they finish. Write concurrentMap(_:_:), which applies an async function to every element concurrently but returns the results in the original order.

Show solution
func concurrentMap<T: Sendable, U: Sendable>(
    _ items: [T],
    _ transform: @escaping @Sendable (T) async -> U
) async -> [U] {
    await withTaskGroup(of: (Int, U).self) { group in
        for (index, item) in items.enumerated() {
            group.addTask { (index, await transform(item)) }
        }
        var results = [U?](repeating: nil, count: items.count)
        for await (index, result) in group {
            results[index] = result
        }
        return results.map { $0! }
    }
}

let words = await concurrentMap([300, 10, 150]) { ms in
    try? await Task.sleep(for: .milliseconds(ms))
    return "waited \(ms)"
}
assert(words == ["waited 300", "waited 10", "waited 150"])

Each task returns its index with its result, and the results are placed by index into an array of optionals, which is full once the group is done. @Sendable promises the compiler that transform is safe to call from several tasks at once, which Swift 6 requires for closures handed to other tasks.

Q3: A shared bank account

Write an actor BankAccount with a balance, a deposit(_:) method, and a withdraw(_:) method that throws InsufficientFunds if there is not enough money. Test it with 100 concurrent deposits of 1 and 150 concurrent withdrawals of 1, starting from 0: some withdrawals must fail, and the balance must never go below zero.

Show solution
struct InsufficientFunds: Error {}

actor BankAccount {
    private(set) var balance = 0

    func deposit(_ amount: Int) {
        balance += amount
    }

    func withdraw(_ amount: Int) throws {
        guard balance >= amount else {
            throw InsufficientFunds()
        }
        balance -= amount
    }
}

let account = BankAccount()
let succeeded = await withTaskGroup(of: Bool.self) { group in
    for _ in 1...100 {
        group.addTask {
            await account.deposit(1)
            return false
        }
    }
    for _ in 1...150 {
        group.addTask {
            (try? await account.withdraw(1)) != nil
        }
    }
    var count = 0
    for await withdrew in group where withdrew {
        count += 1
    }
    return count
}

let balance = await account.balance
assert(balance >= 0)
assert(balance == 100 - succeeded)

How many withdrawals succeed depends on how the tasks interleave, so the test checks what must be true in every run: the books balance. Because the check and the change in withdraw happen with no await between them, no other task can withdraw in between, so the balance can never go negative.

Q4: A time limit

Write withTimeout(milliseconds:_:), which runs an async operation and returns its result, or throws TimedOut if it takes longer than the limit. Race the operation against a sleep in a throwing task group, take the first result, and cancel the loser.

Show solution
struct TimedOut: Error {}

func withTimeout<T: Sendable>(
    milliseconds: Int,
    _ 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: .milliseconds(milliseconds))
            throw TimedOut()
        }
        let first = try await group.next()!
        group.cancelAll()
        return first
    }
}

let quick = try await withTimeout(milliseconds: 500) {
    try await Task.sleep(for: .milliseconds(10))
    return "done"
}
assert(quick == "done")

do {
    _ = try await withTimeout(milliseconds: 20) {
        try await Task.sleep(for: .milliseconds(1000))
        return "too late"
    }
    assert(false, "should have timed out")
} catch {
    assert(error is TimedOut)
}

Whichever child finishes first decides the outcome: a value, or the TimedOut error, which group.next() rethrows. cancelAll() then stops the other one; the slow operation’s Task.sleep throws CancellationError right away, so the group does not wait the full second before returning.

Q5: Rate limiting

A server allows only a few requests at a time. Write fetchLimited(_:maxConcurrent:), which fetches every page with at most maxConcurrent downloads in progress at once, and returns the sizes in the original order. Start maxConcurrent tasks; each time one finishes, start the next. Use the actor provided to check the limit.

actor Monitor {
    private var running = 0
    private(set) var peak = 0

    func start() {
        running += 1
        peak = max(peak, running)
    }

    func stop() {
        running -= 1
    }
}
Show solution
actor Monitor {
    private var running = 0
    private(set) var peak = 0

    func start() {
        running += 1
        peak = max(peak, running)
    }

    func stop() {
        running -= 1
    }
}

let monitor = Monitor()

func fetch(_ page: String) async -> Int {
    await monitor.start()
    try? await Task.sleep(for: .milliseconds(30))
    await monitor.stop()
    return page.count
}

func fetchLimited(_ pages: [String], maxConcurrent: Int) async -> [Int] {
    await withTaskGroup(of: (Int, Int).self) { group in
        var next = 0
        func startNext() {
            let index = next
            group.addTask { (index, await fetch(pages[index])) }
            next += 1
        }
        while next < min(maxConcurrent, pages.count) {
            startNext()
        }
        var sizes = [Int](repeating: 0, count: pages.count)
        for await (index, size) in group {
            sizes[index] = size
            if next < pages.count {
                startNext()
            }
        }
        return sizes
    }
}

let pages = ["a", "bb", "ccc", "dddd", "eeeee", "ffffff", "g"]
let sizes = await fetchLimited(pages, maxConcurrent: 3)
assert(sizes == [1, 2, 3, 4, 5, 6, 1])
let peak = await monitor.peak
assert(peak <= 3)

The group is never given more than three tasks at a time: a new one is added only when a result comes back. The Monitor actor records the most downloads ever in progress together, which is how the test can check a limit that is otherwise invisible.

Q6 (optional): A stream of events

Write ticker(count:every:), an AsyncStream<Int> that yields 1 through count, waiting between them. Then write sumOfFirst(_:in:), which adds up the first n elements of any AsyncStream<Int> and stops listening after that.

Show solution
func ticker(count: Int, every milliseconds: Int) -> AsyncStream<Int> {
    AsyncStream { continuation in
        let task = Task {
            for n in 1...count {
                continuation.yield(n)
                try? await Task.sleep(for: .milliseconds(milliseconds))
            }
            continuation.finish()
        }
        continuation.onTermination = { _ in task.cancel() }
    }
}

func sumOfFirst(_ n: Int, in stream: AsyncStream<Int>) async -> Int {
    var sum = 0
    for await value in stream.prefix(n) {
        sum += value
    }
    return sum
}

let all = await sumOfFirst(100, in: ticker(count: 5, every: 5))
let some = await sumOfFirst(3, in: ticker(count: 1000, every: 5))
assert(all == 15)   // the stream ends after 5
assert(some == 6)   // 1 + 2 + 3, then stop listening

prefix(n) works on asynchronous sequences just as on ordinary ones. When the consumer stops after three elements, the stream is terminated, and onTermination cancels the producing task, so the ticker does not go on counting to 1000 for nobody.

What’s next

Concurrent code is exactly where bugs hide best, because they appear only for some orderings of events. Next lesson: testing, and how to know a program is right.