Concurrency
Estimate how long concurrent code takes, find a data race and fix it with an actor, spot a bug that hides across an await, and compute a maximum with a task group.
This discussion goes with Lesson 22.
Q1: What would Swift print?
What would Swift print?
func square(_ n: Int) async -> Int {
try? await Task.sleep(for: .milliseconds(10 * (4 - n)))
return n * n
}
async let a = square(1)
async let b = square(2)
async let c = square(3)
print(await [a, b, c])Show answer and explanation
Answer[1, 4, 9]
c finishes first and a last, but the array lists the values in the order
written. async let changes when work happens, never which value a name
refers to.
What would Swift print?
actor Log {
var entries: [String] = []
func add(_ entry: String) {
entries.append(entry)
}
}
let log = Log()
await withTaskGroup(of: Void.self) { group in
for word in ["a", "b", "c"] {
group.addTask { await log.add(word) }
}
}
print(await log.entries.sorted(), await log.entries.count)Show answer and explanation
Answer["a", "b", "c"] 3
The order of the entries depends on which task runs first, so the program sorts them before printing. The count is always 3: the actor never loses an append.
Q2: How long does it take?
work(ms) sleeps for ms milliseconds and returns it. Roughly how long does
each snippet take?
// 1
let x = await work(100)
let y = await work(200)
// 2
async let x = work(100)
async let y = work(200)
let total = await x + y
// 3
async let x = work(100)
let y = await work(200)
let total = await x + y
// 4
let total = await withTaskGroup(of: Int.self) { group in
for ms in [100, 200, 300] {
group.addTask { await work(ms) }
}
return await group.reduce(0, +)
}
// 5
var total = 0
for ms in [100, 200, 300] {
total += await work(ms)
}
Show solution
- 300 ms. Each
awaitwaits for its call to finish before the next line starts. - 200 ms. Both start immediately; the total waits for the slower one.
- 200 ms.
xstarts in the background, then the current task waits 200 fory, by which timexis long done. - 300 ms, the slowest of the three, which all run at once. A task group
is an async sequence, so
reduceworks on it. - 600 ms. A loop with
awaitinside is sequential, however the code looks.
Concurrent work takes about as long as the slowest piece; sequential work takes the sum.
Q3: Find the race
This code is meant to count words in several documents at once. Swift 6 refuses to compile it. Explain what could go wrong if it did compile, then fix it with an actor.
final class Tally {
var counts: [String: Int] = [:]
}
let tally = Tally()
await withTaskGroup(of: Void.self) { group in
for document in documents {
group.addTask {
for word in document.split(separator: " ") {
tally.counts[String(word), default: 0] += 1
}
}
}
}
Show solution
Several tasks may update tally.counts at the same moment. An update is a
read (the old count), a change, and a write. If two tasks both read 4 for the
same word, both write 5, and one count is lost. Worse, a dictionary that is
changed by two tasks at once can corrupt its storage and crash. Swift 6 rejects
the code because Tally is a class with mutable state, so it is not
Sendable, and it is captured by tasks that may run in parallel.
actor Tally {
private(set) var counts: [String: Int] = [:]
func add(_ words: [String]) {
for word in words {
counts[word, default: 0] += 1
}
}
}
let documents = ["the cat sat", "the dog sat", "a cat"]
let tally = Tally()
await withTaskGroup(of: Void.self) { group in
for document in documents {
group.addTask {
await tally.add(document.split(separator: " ").map(String.init))
}
}
}
let counts = await tally.counts
assert(counts["the"] == 2 && counts["cat"] == 2 && counts["sat"] == 2 && counts.count == 5)Passing each document’s whole list of words in one call also means one hop onto the actor per document instead of one per word.
Q4: A bug across an await
This actor sells concert tickets. Each purchase checks that tickets remain, then asks a payment service, which takes time, and then hands out a ticket. It sometimes sells more tickets than exist. Why, when an actor runs only one task at a time? How would you fix it?
actor BoxOffice {
var remaining = 100
func buy(card: String) async throws -> Int {
guard remaining > 0 else {
throw SoldOut()
}
try await charge(card) // takes a while
remaining -= 1
return remaining
}
}
Show solution
An actor runs one task at a time only between suspension points. At
await charge(card), the buy call suspends, and the actor is free to start
other calls to buy. With one ticket left, ten buyers can all pass the
guard before any of them reaches remaining -= 1, and remaining ends at
−9.
The fix is to change the state before suspending, and undo it if the payment fails:
struct SoldOut: Error {}
struct Declined: Error {}
func charge(_ card: String) async throws {
try await Task.sleep(for: .milliseconds(10))
if card == "bad" {
throw Declined()
}
}
actor BoxOffice {
private(set) var remaining: Int
init(tickets: Int) {
remaining = tickets
}
func buy(card: String) async throws -> Int {
guard remaining > 0 else {
throw SoldOut()
}
remaining -= 1 // reserve before suspending
do {
try await charge(card)
} catch {
remaining += 1 // give it back
throw error
}
return remaining
}
}
let office = BoxOffice(tickets: 3)
let sold = await withTaskGroup(of: Bool.self) { group in
for i in 0..<10 {
group.addTask { (try? await office.buy(card: i == 0 ? "bad" : "card \(i)")) != nil }
}
return await group.reduce(0) { $0 + ($1 ? 1 : 0) }
}
let left = await office.remaining
assert(left >= 0 && sold + left == 3)The test checks what must hold in every run. Usually all three tickets sell, but not always: if the declined card holds a reservation at the moment the others check, some of them are turned away, and its ticket comes back afterwards. What can never happen is selling a ticket that does not exist.
This is the actor rule from Lesson 22’s callout: after every await, the
actor’s state may have changed, so a check made before it cannot be trusted
after it.
Q5: The largest result
Write largest(_:_:), which applies an async function to every element
concurrently and returns the largest result, or nil for no elements. Do
not keep all the results: track the largest as they arrive.
Show solution
func largest(_ items: [Int], _ score: @escaping @Sendable (Int) async -> Int) async -> Int? {
await withTaskGroup(of: Int.self) { group in
for item in items {
group.addTask { await score(item) }
}
var best: Int?
for await value in group {
best = max(best ?? value, value)
}
return best
}
}
let best = await largest([3, 1, 4, 1, 5, 9, 2, 6]) { n in
try? await Task.sleep(for: .milliseconds(n))
return (n * 7) % 10
}
let none = await largest([]) { $0 }
assert(best == 8) // 4 gives 28 % 10 = 8
assert(none == nil)The order in which results arrive does not matter, because the maximum of a collection does not depend on order. Operations like this, where the order of combining makes no difference, are the ones that parallelize most easily.