skip to content

Suspension Points and Continuations

async functions suspend at each await without blocking a thread, and async let runs child work in parallel. Interviewers ask what happens at a suspension point and how to wrap a callback.

on this pageshow

explore

questions

5

In Swift, what does `await` mark inside an async function, and what happens to the thread when the function suspends there?

level: juniorimportance: must knowfreq 75%

answer

  1. possible, not certain
  2. suspension is never implicit
  3. the thread is given up, not held
  4. shared state may move between awaits
  5. synchronous code cannot await

basics

~20 s

await marks a possible suspension point. If the call does suspend, the async function gives up its thread instead of blocking it, other work runs there, and the function later resumes, perhaps on another thread, where shared state may have changed.

solid answer

~50 s

In Swift an async function pauses only where the compiler makes you write `await`: a call to an async function, a read of an async property or subscript, or a read of an `async let` value. It is a *possible* suspension point: whether it really suspends depends on the callee at run time. When it does, the function and its async callers give up the thread, which goes on to run other jobs; a nonisolated function may resume on a different thread, while main-actor code resumes on the main actor. Code between two awaits runs without suspending (the one hidden wait is an unawaited `async let` at the end of its scope), but shared state read before an `await` can be stale after it. A synchronous function cannot `await` at all: `'async' call in a function that does not support concurrency`.

code

swift · 24 lines
swift
struct ForecastService {
    func forecast(for city: String) async throws -> String {
        try await Task.sleep(for: .milliseconds(200))  // possible suspension point
        return "Sunny in \(city)"
    }
}

struct Sensor {
    var airQualityIndex: Int {
        get async { 42 }                               // an async getter
    }
}

func loadScreen(service: ForecastService, sensor: Sensor) async throws -> String {
    let title = "Today"                                  // runs without suspending
    let forecast = try await service.forecast(for: "Oslo") // may suspend; the thread is freed
    let index = await sensor.airQualityIndex              // an async property read also needs await
    return "\(title): \(forecast), AQI \(index)"         // may run on a different thread
}

// func refreshTapped(service: ForecastService) {
//     let text = try await service.forecast(for: "Oslo")
//     // error: 'async' call in a function that does not support concurrency
// }

go deeper

for a junior

Recall that await marks where an async function might pause, that the thread is freed while it waits, and that only async code can use await.

for a middle

Explain why it is a possible rather than certain suspension point, what needs the marker, and why the function may resume on another thread.

for a senior

Show the production habits: re-read shared state after an await, never block a thread from async code, and know which blocking calls Swift 6 mode rejects.

for a principal

Weigh how explicit suspension points shape a codebase's async design: where state must be re-validated, and why migration to async runs top-down from callers.

## What `await` marks An **asynchronous function** is declared with `async` after its parameters (`func forecast(for city: String) async throws -> String`; `async` goes before `throws`). Inside one, Swift can pause execution only at places you have marked with `await`. The Swift book puts it plainly: suspension is never implicit or preemptive. The places that need the marker are: - a call to an `async` function, method or closure, such as `await service.forecast(for: "Oslo")`; - a read of a property or subscript whose getter is `get async` (how such a getter is declared is covered in the lesson on computed properties); - a read of a constant declared with `async let`; - a throwing async call, which takes both markers in the order `try await`; writing `await try` draws the warning `'try' must precede 'await'`. One `await` may cover several async calls in a single expression. An `await` that covers no async operation draws the warning `no 'async' operations occur within 'await' expression`. Forgetting the marker is an error: `expression is 'async' but is not marked with 'await'`. ## Possible, not certain Swift Evolution's async/await proposal calls these **potential suspension points**. The compiler cannot know statically whether a call will really pause, because that depends on the callee's code and on run-time conditions: a cache hit may return at once, while a network read waits. So `await` is a promise about what *might* happen. The real guarantee is the reverse one: code between two `await`s in the same function runs without being suspended. The one hidden exception is the implicit wait for an `async let` child that was never awaited, which happens when its scope ends. A long synchronous loop holds its thread until it ends, and `await Task.yield()` is how you add a suspension point to such a loop on purpose. ## What happens to the thread When the function does suspend, it and all of its async callers give up the thread together. The book calls this *yielding the thread*. The thread does not sit idle waiting for the answer; the runtime uses it for other jobs. When the awaited work finishes, the function is scheduled again: 1. Code runs up to the first `await` and calls the async function. 2. If that call suspends, the thread runs other queued work. 3. When the result is ready, the function resumes after the `await`, with the result assigned. 4. It runs on until the next `await` or until it returns. Where it resumes depends on its isolation. A nonisolated async function runs on the global concurrent executor's threads, so it may resume on a different thread from the one it started on. Code isolated to the main actor resumes on the main actor. Thread identity is therefore not something to rely on across an `await`. Blocking a thread from async code defeats all of this. Foundation marks `Thread.sleep(forTimeInterval:)` and `DispatchSemaphore.wait()` as unavailable from asynchronous contexts: a warning in **Swift 5 language mode**, an error in **Swift 6 language mode**. A C function such as `sleep(_:)` has no such mark and still blocks. The suspending replacement is `try await Task.sleep(for:)`. ## What can change across a suspension | Survives an `await` unchanged | May differ after an `await` | |---|---| | local `let` constants and value-type locals | properties of shared class instances | | the function's parameters | global and static variables | | values already computed into locals | the thread the code runs on | | | an actor's state, if other calls ran meanwhile (covered in the lesson on actors and reentrancy) | The habit to build: re-read shared state after an `await` instead of trusting a copy taken before it. ## Where `await` is allowed Only an asynchronous context can suspend: - the body of an `async` function, method, closure or getter; - the static `main()` of a type marked `@main`, which may be declared `async`; - top-level code in a `main.swift` file, which may use `await` since Swift 5.7; - the closure of a `Task`, which is how synchronous code starts async work (covered in the lesson on tasks). A synchronous function that writes `await` gets `'async' call in a function that does not support concurrency`. The Swift book adds that there is no safe way to wrap async code so that synchronous code can wait for its result, so the migration runs top-down: make the caller `async`, then the functions it calls.

  • Does every `await` actually suspend the function?
    No. `await` marks a *potential* suspension point. A callee that already has its answer, such as a cache hit, can return without suspending, and the function carries on with the same thread. You write `await` because the compiler cannot prove the call will not suspend, so treat every `await` as a place where other code may run.
  • Why does Swift 6 language mode reject `DispatchSemaphore.wait()` inside an async function?
    Foundation marks it `noasync`, so calling it from an asynchronous context draws `instance method 'wait' is unavailable from asynchronous contexts`: a warning in Swift 5 mode, an error in Swift 6 mode. Waiting on a semaphore blocks the thread instead of suspending, which ties up a thread the concurrency runtime needs and can deadlock it. `Thread.sleep(forTimeInterval:)` is marked the same way; use `try await Task.sleep(for:)`.
  • If a function reads `cache.count` before an `await` and again after it, can the two reads differ?
    Yes, when `cache` is shared mutable state. While the function was suspended, other code ran and could have changed it. Only locals and value-type copies the function owns are certain to be unchanged. Re-read shared state after the `await`, or keep the read and the update together with no `await` in between.

  • await blocks the current thread until the called function returns
  • Every await is guaranteed to suspend the function
  • An async function always resumes on the thread it started on
  • Swift can suspend an async function between any two lines, even synchronous ones
  • A synchronous function can call an async one by adding await
  • A value read from a shared object before an await is still current after it

Assumes Swift 6.4; Foundation's noasync blocking calls are warnings in Swift 5 language mode and errors in Swift 6 language mode.

open as a page

On a Swift forecast screen that needs a forecast and an air-quality reading, how do two sequential awaits differ from two `async let` bindings?

level: middleimportance: must knowfreq 65%

basics

~20 s

Sequential awaits run the requests in turn, so the wait is their sum. Each async let starts its call at once as a child task, awaited where the value is used, so the wait is roughly the slower request.

open as a page

How do you wrap a legacy Swift location SDK's `requestLocation(completion:)` callback in an `async throws` function using `withCheckedThrowingContinuation`?

level: middleimportance: must knowfreq 60%

basics

~10 s

Call the SDK inside withCheckedThrowingContinuation and, in its completion handler, resume the continuation exactly once: resume(returning:) with the location or resume(throwing:) with the error. Callers then simply try await the wrapper.

open as a page

A Swift `headline(compact:)` function starts `async let air` and returns early without awaiting it; why does that return still take two seconds?

level: seniorimportance: should knowfreq 35%

basics

~20 s

An async let child task cannot outlive its scope. On the early return Swift cancels the unawaited child and then waits for it to finish; cancellation is cooperative, so a child that never checks it runs its full two seconds.

open as a page

A Swift async wrapper around a location SDK sometimes hangs forever and sometimes crashes with SWIFT TASK CONTINUATION MISUSE; what causes each, and how do you fix them?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A continuation must be resumed exactly once. A path that never resumes leaves the caller suspended forever, and CheckedContinuation only logs that leak when its last reference is released; a second resume traps. Resume on every path, then drop the continuation.

open as a page