Concurrency and testing
Count words across documents in parallel, share one computation among many callers with an actor, test concurrent code with properties, control time in a rate limiter’s tests, and sort in parallel.
- Lessons
- Concurrency with async and await · Testing
This homework uses Lessons 22 and 23. Put everything in hw10.swift with the
assert lines, and run it. Concurrent code can pass a test by luck, so the
tests here check properties that must hold in every ordering of events,
not just the one that happened.
Q1: Word counts in parallel
Write wordCounts(_:), which counts the words of several documents
concurrently, one child task per document, and merges the per-document
counts into one dictionary. Words are separated by spaces, and case does not
matter.
Show solution
func count(_ document: String) -> [String: Int] {
var counts: [String: Int] = [:]
for word in document.lowercased().split(separator: " ") {
counts[String(word), default: 0] += 1
}
return counts
}
func wordCounts(_ documents: [String]) async -> [String: Int] {
await withTaskGroup(of: [String: Int].self) { group in
for document in documents {
group.addTask { count(document) }
}
var total: [String: Int] = [:]
for await partial in group {
total.merge(partial, uniquingKeysWith: +)
}
return total
}
}
let counts = await wordCounts(["The cat sat", "the dog", "A cat and a dog"])
assert(counts == ["the": 2, "cat": 2, "sat": 1, "dog": 2, "a": 2, "and": 1])
let empty = await wordCounts([])
assert(empty.isEmpty)No actor is needed: each task builds its own dictionary, and only the
group’s own loop, which runs in one task, merges them. Giving each task its
own data and combining at the end avoids shared mutable state entirely,
which is the simplest way to be free of data races.
merge(_:uniquingKeysWith:) adds the counts for words that appear in both.
Q2: Asking only once
Several parts of an app may ask for the same slow result at the same time,
such as a user’s profile. Write an actor Loader whose value(for:) calls
the provided load function at most once per key, even when many
callers ask concurrently before the first load has finished. Store the
in-progress Task for each key, and let later callers await the same task.
Show solution
actor Loader {
private var tasks: [String: Task<Int, Never>] = [:]
private(set) var loads = 0
private let load: @Sendable (String) async -> Int
init(load: @escaping @Sendable (String) async -> Int) {
self.load = load
}
func value(for key: String) async -> Int {
if let existing = tasks[key] {
return await existing.value
}
loads += 1
let task = Task { await load(key) }
tasks[key] = task
return await task.value
}
}
let loader = Loader { key in
try? await Task.sleep(for: .milliseconds(50))
return key.count
}
let results = await withTaskGroup(of: Int.self) { group in
for key in ["ada", "alan", "ada", "ada", "alan", "grace"] {
group.addTask { await loader.value(for: key) }
}
return await group.reduce(0, +)
}
let loads = await loader.loads
assert(results == 3 + 4 + 3 + 3 + 4 + 5)
assert(loads == 3) // one per distinct keyThe important detail is where the task is stored: before the first
await. The check and the store run without suspending, so the next caller
for the same key is guaranteed to find the task, even though the load itself
has not finished. Storing the result after awaiting it would let every
concurrent caller start its own load: Discussion 10’s ticket bug in another
form.
Q3: Testing a concurrent map
Lesson 22’s lab wrote concurrentMap. Test it with a property: for random
arrays of 0 to 20 numbers, with a random delay for each element,
concurrentMap must return exactly what map returns. Use a seeded
generator so failures can be reproduced.
Show solution
struct SeededGenerator: RandomNumberGenerator {
var state: UInt64
mutating func next() -> UInt64 {
state &+= 0x9E3779B97F4A7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9
z = (z ^ (z >> 27)) &* 0x94D049BB133111EB
return z ^ (z >> 31)
}
}
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! }
}
}
var random = SeededGenerator(state: 2026)
for trial in 1...20 {
let input = (0..<Int.random(in: 0...20, using: &random)).map { _ in
(value: Int.random(in: -50...50, using: &random), delay: Int.random(in: 0...5, using: &random))
}
let expected = input.map { $0.value * $0.value }
let actual = await concurrentMap(input) { item in
try? await Task.sleep(for: .milliseconds(item.delay))
return item.value * item.value
}
assert(actual == expected, "trial \(trial): \(input)")
}Random delays make the tasks finish in a different order each trial, which
is exactly what could break a wrong implementation, such as one that
appended results as they arrived. The delays come from the seeded generator,
but the actual timing still varies from run to run, so this test is not
perfectly repeatable. That is normal for concurrent code, and is why the
property compares against plain map instead of a fixed order of events.
Q4: A rate limiter with a fake clock
A token bucket limits how often something may happen. The bucket holds
up to capacity tokens and gains perSecond tokens each second (never going
over capacity). Each request takes one token, and is refused if the bucket is
empty. Write TokenBucket, taking the current time, in seconds, from a
function passed to its initializer, and test it with a clock you control.
Show solution
struct TokenBucket {
let capacity: Double
let perSecond: Double
private let now: () -> Double
private var tokens: Double
private var lastRefill: Double
init(capacity: Int, perSecond: Double, now: @escaping () -> Double) {
self.capacity = Double(capacity)
self.perSecond = perSecond
self.now = now
tokens = Double(capacity)
lastRefill = now()
}
mutating func allow() -> Bool {
let time = now()
tokens = min(capacity, tokens + (time - lastRefill) * perSecond)
lastRefill = time
guard tokens >= 1 else {
return false
}
tokens -= 1
return true
}
}
final class FakeClock {
var time = 0.0
}
let clock = FakeClock()
var bucket = TokenBucket(capacity: 3, perSecond: 2) { clock.time }
assert([bucket.allow(), bucket.allow(), bucket.allow(), bucket.allow()] == [true, true, true, false])
clock.time = 0.5 // half a second: one new token
assert(bucket.allow() && !bucket.allow())
clock.time = 100 // a long pause refills to capacity, not beyond
assert([bucket.allow(), bucket.allow(), bucket.allow(), bucket.allow()] == [true, true, true, false])With a real clock, testing the refill would mean sleeping, and the result
would depend on how fast the computer is. The fake clock makes time a value
the test sets, so the test runs instantly and gives the same answer every
time. FakeClock is a class, so the closure and the test share it.
Q5 (optional): Parallel merge sort
Write parallelSort(_:), a merge sort that sorts the two halves
concurrently with async let, falling back to sorted() for arrays of 1,000
elements or fewer, where starting tasks would cost more than it saves. Test
it against sorted() on random arrays.
Show solution
func merge(_ a: [Int], _ b: [Int]) -> [Int] {
var result: [Int] = []
result.reserveCapacity(a.count + b.count)
var i = 0
var j = 0
while i < a.count && j < b.count {
if a[i] <= b[j] {
result.append(a[i])
i += 1
} else {
result.append(b[j])
j += 1
}
}
return result + a[i...] + b[j...]
}
func parallelSort(_ values: [Int]) async -> [Int] {
guard values.count > 1000 else {
return values.sorted()
}
let middle = values.count / 2
async let left = parallelSort(Array(values[..<middle]))
async let right = parallelSort(Array(values[middle...]))
return await merge(left, right)
}
var generator = SystemRandomNumberGenerator()
for size in [0, 1, 999, 1001, 20_000] {
let values = (0..<size).map { _ in Int.random(in: -1000...1000, using: &generator) }
let sorted = await parallelSort(values)
assert(sorted == values.sorted(), "size \(size)")
}The sizes are chosen at the boundaries: empty, one element, just under and just over the threshold, and one large enough to split several times. Each level of recursion splits into two tasks, so a 20,000-element array ends in 32 small sorts, which the runtime spreads over as many cores as the machine has.