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
- Documentation
- Task · TaskGroup · Actor · AsyncStream · Swift 6 migration guide
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
asynccode can callasyncfunctions. The top level of a script counts as async code, which is whyawaitworks above. awaitmarks every possible suspension point, the waytrymarks every possible early exit. Between twoawaits, code runs without interruption.- A function can be both:
async throws, called withtry 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)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)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.isCancelledistrueonce the current task has been cancelled.try Task.checkCancellation()throws aCancellationErrorif it has.Task.sleepand many other waiting functions throwCancellationErrorimmediately 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.
}let b = await triple(a)async let a = triple(1)print(b + 3)n * 3func 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)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)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 listeningprefix(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.