DocsLanguage Guide
Concurrency
async and await, structured tasks, cancellation, actors, Sendable and threads.
Sable has concurrency built into the language: asynchronous functions that suspend instead of blocking, tasks that run alongside each other in a structured tree, actors that protect their state by running one call at a time, and a Sendable check that makes data races on shared state a compile-time error rather than a bug you find in production.
The design follows Swift's closely, because Swift's is well understood: async and await, async let, task groups, actors and Sendable all mean what they mean there. On top of that, Sable's Sable.Concurrency library gives you real threads, scoped threads and parallel loops for CPU-bound work, with the same Sendable rules.
Asynchronous Functions#
An asynchronous function can suspend part way through, while it waits for something — a network reply, a timer, another task — and let other work run on its thread meanwhile. You mark one with async, before fn or after the parameters:
async fn fetchQuote(for symbol: String) -> F64 { try? await Task.sleep(nanoseconds: 1_000_000) return 101.5}fn fetchVolume(for symbol: String) async throws(FeedError) -> Int { return 4_200}Both spellings mean the same. A throwing async function writes async before throws, as the second one does.
Calling an async function is a suspension point, and you mark it with await, so that every place a function might pause is visible in its source:
async fn report(_ symbol: String) throws(FeedError) -> String { let price = await fetchQuote(for: symbol) let volume = try await fetchVolume(for: symbol) return "\(symbol): \(price) × \(volume)"}try and await combine, try first. Only async code can call async code: calling fetchQuote from an ordinary function is an error (S3035), and so is leaving out the await (S3034).
Async function types are written with async in front: async (Request) throws(HttpError) -> Response. A closure that awaits is async, and when two overloads differ only in whether the closure they take is async, the closure decides which is called.
Note
An async function doesn't run on its own thread. It is compiled into a state machine, so a suspended call holds only the values it still needs, in a frame on its task's slab. Thousands of waiting tasks cost memory, not threads.
An Async Entry Point#
A program whose main is async can await from its first line:
@mainasync fn main() { do { print(try await report("SBL")) } catch { print("no quote") }}The runtime starts a thread pool sized to the machine's processors, runs main as the first task, and waits for every task before it exits. SABLE_WORKERS=n sets the pool's size; SABLE_WORKERS=0 runs every task on the main thread in a deterministic order, which is useful when you are debugging.
Running Work Alongside: async let#
A call with await runs one thing at a time: the caller waits for each in turn. To run several at once, start each with async let:
async fn dashboard() -> String { async let price = fetchQuote(for: "SBL") async let rival = fetchQuote(for: "GRN") async let news = latestHeadline() return "\(await price) vs \(await rival): \(await news)"}async let is a statement, not an expression. Each one starts a child task at once, running the expression on the right alongside the code that follows. That expression is the child's work, so it may await and throw without writing await or try itself.
Reading the name waits for the child to finish and gives its value. You write await where you read it, and try as well when its work can throw:
async fn both() throws(FeedError) -> Int { async let a = fetchVolume(for: "SBL") async let b = fetchVolume(for: "GRN") return try await a + try await b}An error the child throws comes out where its name is read. A tuple of them is awaited together: let both = try await (a, b).
An async let is bound to the scope it's declared in. A child that is never read, or that is left behind by a return or a throw, is cancelled and then awaited as the scope ends, so it never outlives the function that started it. For the same reason an async let can only be read in the scope it was declared in, not from a closure that might run later (S3235).
Task Groups#
async let suits a fixed number of children. When the number depends on the data, use a task group:
async fn fetchAll(_ symbols: String[]) -> [String: F64] { return await withTaskGroup(of: (String, F64).self) { group in for symbol in symbols { group.spawn { (symbol, await fetchQuote(for: symbol)) } } var prices: [String: F64] = [:] for await (symbol, price) in group { prices[symbol] = price } return prices }}withTaskGroup(of:) runs a body with a group whose children each give a value of the type named. spawn adds a child (spawn(priority:) with another priority). The group is an AsyncSequence of the children's results, in the order they finish, not the order they were spawned: go through it with for await, or ask for one at a time with await group.next(), which gives none when none are left. waitForAll() waits without collecting, isEmpty says whether any are left, and cancelAll() cancels every child still running.
When the body returns, any children it didn't wait for are awaited first, so none outlives the group.
withThrowingTaskGroup(of:) is the same for children that throw. Its results are gone through with for try await or try await group.next(), and the first error read is thrown on. If the body throws, the remaining children are cancelled before they are awaited:
async fn totalVolume(_ symbols: String[]) throws -> Int { return try await withThrowingTaskGroup(of: Int.self) { group in for symbol in symbols { group.spawn { try await fetchVolume(for: symbol) } } var total = 0 for try await volume in group { total += volume } return total }}Unstructured Tasks#
Task.spawn starts a task without waiting for it, and gives back a Task<T> handle. You read its result later with await task.value:
async fn warmCache() { let loading = Task.spawn { await loadIndex() } prepareScreen() let index = await loading.value print("\(index.count) entries")}Even though nothing waits for it at once, a spawned task is still a child of the task that spawned it: it is cancelled with its parent, and its parent doesn't finish until it has.
Task.detached is the one way to start a task with no parent. It isn't cancelled with anything, and nothing waits for it but the program's exit. Reach for it rarely: a task in the tree is easier to reason about.
let poller = Task.detached { await pollForever() }Priorities#
A task runs at a TaskPriority: .high, .medium (the default for a task with no parent), .low or .background. A child takes its parent's priority unless you give it another, Task.spawn(priority: .low) { … }, and Task.currentPriority reads the running task's. The runtime orders its run queues by priority, and a task waiting on a lower-priority one raises that task's priority, and its children's, so that it doesn't invert.
Small Helpers#
Task has a few static helpers that come up often:
| Helper | What it does |
|---|---|
await Task.yield() |
Lets other tasks run before carrying on |
try await Task.sleep(nanoseconds:) |
Suspends for a time; throws CancellationError once cancelled |
await Task.limited(nanoseconds:) { … } |
Runs a body, giving none if it takes longer |
await Task.blocking { … } |
Runs blocking work off the pool (see below) |
Cancellation#
Cancellation in Sable is cooperative. task.cancel() marks a task, and all of its children, as cancelled; it doesn't stop anything by force. Each task checks for itself and stops where it makes sense:
async fn indexEverything(_ files: String[]) throws(CancellationError) -> Int { var indexed = 0 for file in files { try Task.checkCancellation() await index(file) indexed += 1 } return indexed}There are three ways to notice:
Task.isCancelledis aBoolyou can test.try Task.checkCancellation()throwsCancellationErrorif the task is cancelled.- A
Task.sleepthe task is in ends at once and throwsCancellationError.
Cancelling is fast to ask for and costs nothing until a task looks. A loop that runs until it is told to stop looks like this:
async fn heartbeat() { while !Task.isCancelled { sendPing() try? await Task.sleep(nanoseconds: 1_000_000_000) }}let beating = Task.spawn { await heartbeat() }// … laterbeating.cancel()When the work you're waiting on isn't Sable's to stop — a callback from C, a request in flight — withTaskCancellationHandler(operation:onCancel:) runs a handler as the task is cancelled (at once, if it already is), while the operation runs:
let body = try await withTaskCancellationHandler(operation: { try await request.response()}, onCancel: { request.abort()})Actors#
Tasks that share mutable state need to take turns. An actor is a reference type, like a class, that does it for you: it runs one call at a time, so its state is never seen half-changed.
actor Inventory { private var stock: [String: Int] = [:] nonisolated let warehouse: String init(warehouse: String) { self.warehouse = warehouse } fn add(_ sku: String, count: Int) { stock[sku] = (stock[sku] ?? 0) + count } fn take(_ sku: String) -> Bool { guard let left = stock[sku], left > 0 else { return false } stock[sku] = left - 1 return true }}Inside the actor, its methods use its state directly, and a call one of them makes to another doesn't wait. From outside, every call into the actor, and every read of its state, waits its turn, so it is written with await:
let depot = Inventory(warehouse: "North")await depot.add("lamp", count: 2)let gotOne = await depot.take("lamp")print(depot.warehouse) // nonisolated: no awaitCode outside an actor can never assign to its state (S3206); only the actor changes it. A nonisolated member — an immutable let, or a computed property or method that touches no isolated state — belongs to no turn and is used without await.
Reentrancy#
An actor is reentrant at its suspension points. When one of its methods awaits something, it lets the actor go, so other calls can run meanwhile, and takes it back before it carries on. That keeps actors from deadlocking, but it means state you read before an await may have changed after it:
actor Account { var balance = 100 fn withdraw(_ amount: Int) async -> Bool { guard balance >= amount else { return false } await audit(amount) // others may run here … guard balance >= amount else { // … so check again return false } balance -= amount return true }}Keep the check and the change on the same side of an await, or check again after it.
Actors and Protocols#
An actor's isolated method can satisfy a protocol's async requirement: callers await it anyway, and a call through a generic or an existential hops into the actor just as a direct call does. It can't satisfy a synchronous requirement, whose callers wouldn't wait for their turn (S3237).
The Main Actor#
@MainActor pins a declaration — a function, a class, any declaration — to the main actor: the main thread, which runs the program's entry. Code elsewhere calls into it with await, as it would into any actor. User-interface code, which toolkits require to run on the main thread, is the usual reason:
@MainActorclass StatusBar { var text = "" fn show(_ message: String) { text = message }}async fn finished(_ bar: StatusBar) { await bar.show("done")}Sendable#
A value that crosses from one task, actor or thread to another — an isolation boundary — must be safe to share. Sendable is the protocol that says so, and the compiler checks every crossing.
Conformance is structural, worked out from what a type is made of:
- Numbers,
Bool,CharandStringare Sendable. - A struct, union, tuple, optional or array is Sendable when everything in it is.
- A class is not Sendable, because two tasks holding it could change its state at once. An
@immutableclass (deeply immutable), an actor, and a@MainActorclass are.
A type that declares : Sendable is checked where it is declared (S3410), and the message says which field is the problem:
class Cursor { var position = 0}struct Job: Sendable { // error[S3410]: 'Job' cannot be Sendable: its field 'cursor' has type 'Cursor', which is not Sendable var cursor: Cursor}What crosses an actor's boundary — the arguments of a call into it, and what the call returns — must be Sendable too (S3207).
Closures That Run as Tasks#
A task's closure — Task.spawn's, Task.detached's, a group's spawn's, Task.blocking's, and the work of an async let — crosses a boundary. What it captures must be Sendable, and it may capture a var only by value, never by reference (S3236), since two tasks writing the same variable is a race. An inout parameter, and self in a mutating method, count as a var.
async fn tally(_ words: String[]) -> Int { var count = 0 let t = Task.spawn { count += words.count // error[S3236]: 'count' is a 'var' } await t.value return count}Return the value from the task instead: let count = await Task.spawn { words.count }.value.
When you write a function that runs a closure parameter as a task, mark the parameter's type @Sendable. It then takes a closure written right there, a named function, or another @Sendable parameter, and the closure's captures are checked:
fn retrying<T: Sendable>(_ times: Int, _ body: @Sendable async () -> T?) async -> T? { for _ in 0..<times { if let value = await Task.spawn(body).value { return value } } return none}Inside an unsafe block, you vouch for what is shared, and the check is not made. You take on the job of making sure nothing races.
Atomic Reference Counts#
Reference counting is cheap because most objects are only ever counted by one thread. Sable keeps it that way: an object's counts become atomic only once it is shared, a mark it gets (along with everything it reaches) as it first crosses to another task or thread. Objects that never leave their task are counted with plain loads and stores. You don't write anything for this; it is how the Memory and Ownership model keeps ARC fast under concurrency.
Asynchronous Sequences#
An AsyncSequence is a sequence whose next element may have to be waited for: lines from a socket, messages from a channel, the results of a task group. You go through one with for await:
for await message in inbox { handle(message)}A sequence whose Failure isn't Never — one that may fail as it goes — is gone through with for try await, inside a function that may throw what it throws.
AsyncStream (in Sable.Concurrency) is the simplest way to make one: a stream and a continuation that any code can yield values to and finish:
import Sable.Concurrencylet (stream, continuation) = AsyncStream<Int>.make()let producer = Task.spawn { for i in 1...3 { continuation.yield(i) } continuation.finish()}var total = 0for await value in stream { total += value}await producer.valueprint(total) // 6Async Generators#
The generators you met in Functions have an async kind. An async function whose result is some AsyncSequence<T> and whose body uses yield is an async generator: its body can await between elements, and nothing runs until someone asks for the first one:
async fn ticks(every nanoseconds: Int, count: Int) -> some AsyncSequence<Int> { for i in 0..<count { try? await Task.sleep(nanoseconds: nanoseconds) yield i }}for await tick in ticks(every: 1_000_000, count: 3) { print("tick \(tick)")}Sable.Core and Sable.Concurrency add the usual operators on async sequences (map, filter, prefix, zip, merging, debouncing and more), and channels for passing values between tasks.
Threads and Parallel Loops#
Tasks are for work that waits. For work that computes — the kind that keeps a processor busy — Sable.Concurrency gives you threads and parallel loops. Their closures follow the same Sendable rules as a task's.
Blocking Work#
A task that blocks its thread, for a call into C that waits or a whole file read at once, keeps a worker from every other task. Task.blocking runs such work on a separate pool kept for it, while the calling task suspends:
fn checksum(_ path: String) async throws(IoError) -> U64 { return try await Task.blocking { try hashFile(path) }}The body runs as the calling task (it can ask Task.isCancelled) but on another thread, so what it captures must be Sendable.
Threads#
Thread.spawn starts an operating-system thread and gives a JoinHandle. join() blocks until it ends and gives what the body returned, or throws what it threw; async code awaits value() instead, so as not to block a worker:
import Sable.Concurrencylet handle = Thread.spawn(name: "crunch") { var total = 0 for i in 1...1_000_000 { total += i } return total}print(handle.join()) // 500000500000A thread can also be given a stackSize (at least 256 KiB) and a priority, a hint to the system. join(atMost:) waits for a while, isFinished asks, and detach() lets it go. A program waits for every thread it started before it exits, joined or not. Thread.current, Thread.sleep, Thread.yield() and Thread.availableParallelism (the processors the process may use) are there too.
A thread has a task of its own running on it, so it can spawn tasks; Thread.blockOn { … } runs an async body from a thread and blocks until it's done.
Scoped Threads#
Thread.scope runs a body with a scope, and doesn't return until every thread spawned on the scope has ended. Because the threads can't outlive it, a thread spawned in a scope may use a var of the function around it, which is that thread's alone until the scope ends:
var log: String[>..] = []Thread.scope { s in s.spawn(name: "writer") { log.append("written from a thread") }}print(log) // ["written from a thread"]The compiler checks that the var really is the one thread's: it belongs to the calling function, the thread is spawned in the scope's own closure and not in a loop, and nothing else in the scope or in another closure of the function mentions it (S3236). This is stricter than Rust's scoped threads: threads that only read share a let, and the variable can be used again only once the scope has ended.
Parallel Loops#
For data-parallel work, parallelFor runs a body for each index of a range across the pool's workers and the calling thread, and returns once all are done:
parallelFor(0..<8) { i in renderTile(i)}var pixels = F32[>..](repeating: 0.5, count: 1_000_000)pixels.parallelModify { $0 = $0 * $0 } // each element changed where it isparallelForChunks gives the body a range at a time, parallelInvoke runs two to four closures at once and gives back their results, and parallelForEach runs an async body over a sequence with a bounded number of child tasks. Each takes a degree (how many threads at most) and most a grain (the fewest elements in a chunk).
An array's or a range's parallel gives the familiar operations, divided between threads, with their results in order:
let words = ["a", "list", "of", "words"]print(words.parallel.map { $0.count }) // [1, 4, 2, 5]print(words.parallel.filter { $0.count > 1 }) // ["list", "of", "words"]print((0..<101).parallel.sum()) // 5050map, filter, compactMap, flatMap, forEach, reduce, sum, min, max, count(where:), first(where:), contains(where:), allSatisfy and sorted are all there; withDegree(_:) limits the threads and unordered gives results as they are ready. The elements are cut into the same chunks each time and combined in order, so even a sum of floats gives the same answer every run. parallelModify, parallelSort and parallelModifyChunks(of:) change an array's elements where they are.
If a body throws, no more chunks are begun, and the first error is thrown once the threads have stopped. A loop's chunks run as children of the task that began it, so Task.checkCancellation() in the body ends the loop when the task is cancelled. With no pool (SABLE_WORKERS=0) a loop just runs in order on its own thread.
Thread and Task Locals#
ThreadLocal<T> holds a value per thread, made when first asked for and destroyed as the thread ends; TaskLocal<T> holds one per task, bound with withValue(_:_:) for as long as its body runs, and inherited by child tasks (a detached task and a thread start with none). Use them for context such as a request's identifier that you'd otherwise pass through every call.