.\" Made by website/plain/build.mjs from website/words/async.md; change that file. .TH SG-ASYNC 7 2026-11-28 "SG" "SG reference" .SH NAME async \- makes a function a light task, which may await and never holds its thread .SH SYNOPSIS .TP \fBasync T name(...) { ... }\fR an async function: a call gives a Task .TP \fBasync void name(...) { ... }\fR one that gives nothing: a call gives a Task .TP \fBasync void main()\fR a program whose main may await .TP \fBasync T name(read this, ...)\fR an async method that lends this: it is awaited where it is called .TP \fBasync T name(this, ...)\fR an async method that takes this: a call may start it as a task .TP \fBvar t = f(x)\fR starts f as a task, which runs until it first waits .TP \fBawait f(x)\fR runs f as part of this task, and gives what it returns .TP \fBf(x).wait()\fR waits for it from code that is not async .SH DESCRIPTION \fBasync\fR in front of a function makes each call of it a light task. A call gives a \fBTask\fR, where \fBT\fR is the type written after \fBasync\fR\&. The task starts at once and runs on the caller until it first waits; then the caller goes on. A few threads run many such tasks, since a task that waits gives its thread to another. .PP An async function may \fBawait\fR: wait for a task, a delay (\fBTask.delay(ms)\fR), a channel, a group of tasks, or the async calls of files, the network and other programs. In exchange it never holds its thread. \fBwait\fR, the calls of \fBFile\fR and \fBDirectory\fR, and reading the input are errors there, and so is a call of a function that does one of them. Work that must hold a thread runs apart with \fBawait Task.run(work, x)\fR\&. \fBprint\fR is allowed. .PP A task started without \fBawait\fR follows the rule of every task: what it is given owns all it holds, so no borrow goes to it, and a \fBshared\fR value goes as one more owner. \fBawait f(read xs)\fR ends before the caller goes on, so it may borrow. Every task is waited for, on every path, with \fBawait\fR or with \fBwait\fR\&. .PP An async function is not a value: it is called by its name, not kept in a variable or given to \fBTask.run\fR\&. .SH EXAMPLES .SS "An async function" .RS 4 .nf async int twice(int n) { await Task.delay(10) return n * 2 } async void main() { var answer = await twice(21) print(answer) } .fi .RE .PP .RS 4 .nf 42 .fi .RE .PP \fBtwice\fR waits 10 milliseconds, then returns. \fBmain\fR is async too, so it can \fBawait\fR the call. .SS "A call starts the task at once" .RS 4 .nf async int fetch(string name, int ms) { print($"{name}: asked") await Task.delay(ms) return (int)name.length() } async void main() { var first = fetch("first", 200) var second = fetch("second", 100) print("both asked") print(await first + await second) } .fi .RE .PP .RS 4 .nf first: asked second: asked both asked 11 .fi .RE .PP Each call runs until its first \fBawait\fR, then \fBmain\fR goes on. The two delays run at the same time, so the program takes about 200 milliseconds, not 300. .SS "Waited for by code that is not async" .RS 4 .nf async int twice(int n) { await Task.delay(10) return n * 2 } void main() { var task = twice(21) print(task.wait()) print(twice(4).wait()) } .fi .RE .PP .RS 4 .nf 42 8 .fi .RE .PP A function that is not async cannot \fBawait\fR, but it can call an async function and \fBwait\fR for the task. .SS "Async methods" .RS 4 .nf struct Order { string item int count async int weigh(read this) { await Task.delay(5) return this.count * 250 } async string pack(this) { await Task.delay(10) return $"{this.count} x {this.item}".toString() } } async void main() { var tea = Order { item = "tea", count = 2 } print(await tea.weigh()) var packing = tea.pack() var bread = Order { item = "bread", count = 1 } print(await bread.pack()) print(await packing) } .fi .RE .PP .RS 4 .nf 500 1 x bread 2 x tea .fi .RE .PP \fBweigh\fR lends \fBthis\fR, so it is awaited where it is called. \fBpack\fR takes the order, so \fBtea.pack()\fR starts a task that owns it, and \fBtea\fR is not used after. .SS "Work that holds a thread" .RS 4 .nf long sumSquares(long limit) { long total = 0 for i in 0..limit { total += i * i } return total } async void main() { var heavy = Task.run(sumSquares, 1000000) await Task.delay(10) print("the delay is over") print(await heavy) } .fi .RE .PP .RS 4 .nf the delay is over 333332833333500000 .fi .RE .PP \fBTask.run\fR gives the work a thread of its own, so the async tasks are not held while it counts. Its task is awaited like any other. .SS "Owners of one value in several tasks" .RS 4 .nf struct Config { string greeting int pause } async string greet(shared Config config, string name) { await Task.delay(config.pause) return $"{config.greeting}, {name}".toString() } async void main() { var config = new shared Config { greeting = "Hello", pause = 20 } var first = greet(share config, "Ada") var second = greet(share config, "Pasha") print(await first) print(await second) } .fi .RE .PP .RS 4 .nf Hello, Ada Hello, Pasha .fi .RE .PP A task started without \fBawait\fR cannot borrow \fBconfig\fR, since it could outlive it. \fBshare config\fR gives each task one more owner of the same value, with no copy. .SS "A group of tasks" .RS 4 .nf async void download(int size, shared atomic int total) { await Task.delay(size) _ = total.fetchAdd(size) } async void main() { var total = new shared atomic 0 var sizes = List { 30, 10, 20, 40 } var group = TaskGroup(2) for size in sizes { await group.whenRoom() group.add(download(size, share total)) } await group.whenAll() print($"{total.load()} bytes") } .fi .RE .PP .RS 4 .nf 100 bytes .fi .RE .PP A \fBTaskGroup\fR holds tasks that give nothing and lets go of each as it ends. \fBTaskGroup(2)\fR lets two run at a time: \fBwhenRoom\fR waits until one of them has ended. \fBwhenAll\fR waits for the rest. .SS "A time limit" .RS 4 .nf async Result slowAnswer(int ms, read CancellationToken token) { try await Task.delay(ms, read token) return Ok(42) } async void main() { var limit = CancellationSource() limit.cancelAfter(100) var token = limit.token() print(await slowAnswer(20, read token) ?? -1) print(await slowAnswer(500, read token) ?? -1) print(token.isCancelled()) } .fi .RE .PP .RS 4 .nf 42 -1 true .fi .RE .PP The source cancels itself 100 milliseconds after \fBcancelAfter\fR\&. The first answer comes in time. The second delay is cut short with \fBError(Cancelled { })\fR, which \fBtry\fR passes on. .SH "WHAT THE COMPILER REFUSES" .SS "wait in an async function" .RS 4 .nf async int twice(int n) { await Task.delay(10) return n * 2 } async void main() { var task = twice(21) print(task.wait()) } .fi .RE .PP .RS 4 .nf error: an async function does not `wait`: that would hold the thread, which other tasks need, until the task ends --> example.sg:8:16 8 | print(task.wait()) | ^^^^ hint: `await task` waits without holding the thread .fi .RE .SS "A call that holds the thread" .RS 4 .nf nint size(read string path) { var text = File.readText(read path) ?? "" return text.length() } nint report() { return size("notes.txt") } async void main() { print(report()) } .fi .RE .PP .RS 4 .nf error: `report` holds the thread until it is done, and an async function does not hold its thread the tasks of async functions share a few threads: one that holds its thread keeps the others from running --> example.sg:11:11 11 | print(report()) | ^^^^^^ `report` calls `size`, which does `File.readText` here: --> example.sg:2:21 2 | var text = File.readText(read path) ?? "" | ^^^^^^^^ hint: a function that does it runs on a thread of its own with `await Task.run(work, x)` .fi .RE .PP The compiler follows the calls, and shows the chain that reaches the read. .SS "A borrow given to a task" .RS 4 .nf async int total(read List numbers) { await Task.delay(5) var sum = 0 for n in numbers { sum += n } return sum } async void main() { var numbers = List { 1, 2, 3 } var task = total(read numbers) print(await task) } .fi .RE .PP .RS 4 .nf error: `total` takes a `read List` here, and a call without `await` starts it as a task of its own, which this cannot go to: a `read List` is a borrow, and the task could outlive what it borrows from --> example.sg:12:22 12 | var task = total(read numbers) | ^^^^^^^^^^^^ hint: `await total(read numbers)` runs it as part of this task, where it can borrow .fi .RE .SS "An async function kept as a value" .RS 4 .nf async int answer() { return 42 } void main() { var task = Task.run(answer) print(task.wait()) } .fi .RE .PP .RS 4 .nf error: `answer` is async, and an async function is called by its name, not kept as a value --> example.sg:6:25 6 | var task = Task.run(answer) | ^^^^^^ hint: call it: `answer(...)` starts it as a task, `await answer(...)` runs it here .fi .RE .SS "An async function that awaits itself" .RS 4 .nf async long countdown(int n) { if n == 0 { return 0 } await Task.delay(1) return n + await countdown(n - 1) } async void main() { print(await countdown(3)) } .fi .RE .PP .RS 4 .nf error: the async function `countdown` awaits itself an awaited call runs inside the task of its caller, so a task that holds itself would have no end --> example.sg:6:22 6 | return n + await countdown(n - 1) | ^^^^^^^^^ hint: keep the call's task in a variable, which gives it a task of its own: `var task = f(x)`, then `await task` .fi .RE .PP With \fBvar rest = countdown(n \- 1)\fR and then \fBreturn n + await rest\fR, each call is a task of its own, and the program prints \fB6\fR\&. .SS "async in front of a type" .RS 4 .nf async struct Point { int x } void main() { } .fi .RE .PP .RS 4 .nf error: `async` is written in front of a function --> example.sg:1:1 1 | async struct Point { | ^^^^^ hint: `async int count(string path) { ... }` .fi .RE .SH "SEE ALSO" .BR sg-await (7), .BR sg-shared (7) .PP https://sg\-lang.org/reference/async.html