What does a program do while it waits, and where is the rest of a function while it waits?
Call stack: one frame per call that has not returned: its arguments, its local variables, where to return.
Only the frame on top executes.
Stackless: at an await the frame is popped and its state kept in the heap; one frame is saved.
Goroutines and Java’s virtual threads are stackful: the runtime keeps the whole stack.
Heap: every value that must survive after the frame that created it is popped.
Objects, closures, and the saved state of a suspended function: its local variables and where to resume.
The crux of asynchronous programming: the rest of a function becomes a value.
As a value it can be kept in the heap, with its local variables and the point where to resume.
Queue: the functions that are ready to run and have not run yet.
The queue holds work, not data: a function ready to run, which points to what it needs in the heap.
Nothing moves from the heap to the queue.
Loop: when the stack is empty, takes one function from the queue to the stack and runs it to its end.
When a value arrives, the host queues a function that stores it in the heap.
That queues the rest of the waiting function, which the loop then runs.
The heap remembers, the queue schedules, the loop dispatches, the stack runs.
Host: the browser or the operating system.
It owns the clock and the devices, and it can only append a function to the queue.
A browser appends the function that answers user input, a timer that is due, a network reply, a message.
What resumes after an await goes to a second queue, the microtask queue; we will see both.
A model of what the language guarantees, not of how an engine is built. Two assumptions hold for the whole block.
One thread: all our code runs on it; no other thread runs code of ours.
An uncontrolled environment: the order of the host’s events is not the program’s to fix.
async function load() {
console.log("A");
const user = await fetchUser();
console.log("C", user);
}
load();
console.log("B");
Definition. An asynchronous function can be suspended at the points marked await in its text. At a suspension point its frame leaves the stack; the part that remains to be run, with its local variables, is kept in the heap. The caller resumes.
The word promise is Friedman and Wise’s, 1976, for a lazy suspension; Baker and Hewitt’s future, 1977, is eager; Liskov and Shrira, 1988, gave the promise its typed form for asynchronous remote calls.
The rest, the highlighted line, is kept, registered on the awaited promise: a value that stands for a result to come.
The rest is a function of the awaited value: user => { console.log("C", user); }
Running: on the stack. Suspended: waiting for a value that is not there yet.
Ready: in the queue, its value there, waiting for the loop to run it.
Control passes only where the text says so, at an await: cooperative (Adya et al., 2002).
Threads are preemptive: control can be taken away between any two instructions.
Property 1 · Suspension. An asynchronous function is suspended only at an await written in it. Its caller then goes on with its next statement: after load(); the script prints B.
A caller that writes await load(); is suspended too.
new Promise and await†new Promise(executor): making and settlingconst fetchUser = () =>
new Promise(res =>
setTimeout(() => res("Ada"), 300));
executor at once, with res.res calls res(v), and the promise becomes fulfilled with v.await e: waiting and resumingconst user = await fetchUser();
e. If the result is not a promise, it is wrapped into an already fulfilled one.await p amounts to p.then(rest)*.await e has the promise’s value.load() runs, and reaches await fetchUser().
new Promise creates a promise p in the heap, pending.
It calls the executor with res; the executor gives the host a timer that holds () => res(…).
fetchUser returns p: the expression after await has a promise as its value.
await registers the rest of load() on p.
load() is suspended: its frame leaves the stack, and its caller goes on.
Later, the timer is due: the host puts its function in the task queue.
The loop runs it: res fulfills p, and the rest of load() goes to the microtask queue.
The loop runs the rest: load() resumes, and the await expression has p’s value.
† Python, C# and Rust have the same pair; what differs around it: part 3, and the appendix.
* p.then(f) registers f, to be called with the value of p once p is fulfilled.
Before promises, a function whose result comes later took a callback: the rest of the computation, as a function, which it calls with the result.
await, the steps follow one another.try. Failure: session 9.JavaScript
getK(k, cb) asks for k; cb gets the answer 300 ms later. get is the same request as a promise.
a and b: two requests, each answered after 300 ms; made in turn, or together before either is awaited.
Left blue: on the stack, the call to get creates a promise in the heap and gives the host a timer;
at the await the frame leaves the stack, its saved state goes to the heap.
Hatched: nothing of ours on the stack for this request.
The promise and the saved state are in the heap, the timer counts down in the host.
Right blue: the host queues the timer’s function, which fulfills the promise; that queues the rest,
and the loop puts it back on the stack, its frame rebuilt from the heap, to run with the value.
Property 2 · Waiting is not running. Waits can overlap in time; executions of our code cannot: on one thread*, at any moment at most one computation is running.
Property 3 · Run-to-completion. The loop takes the next function from the queue only when the stack is empty: the running code has returned, and so has everything it called. Running code is never interrupted: it keeps the thread until it returns.
* JavaScript can run code of ours on another thread, a worker, with its own loop and its own heap.
appendixExecution: one sequence of resumptions. One program and one input have as many executions as the environment can produce.
Not a stack: P was suspended first and resumes first, while Q waits. No single stack can hold both: each saved state is in the heap.
Interleaving points are exactly the suspension points. Between two of them, nobody else runs.
Property 4 · Atomicity between suspension points. A stretch of a function’s text with no await in it is atomic with respect to all other code of ours: nobody observes it half done, except the functions it calls, which run inside it; others run only between stretches. Atomic: isolated, not all-or-nothing.
let balance = 100;
async function deposit(n) {
const b = balance;
await approve(n);
balance = b + n;
}
deposit(10);
deposit(20); // required: 130
approve(n) asks another service to approve the deposit; its answer comes 100 ms later.
Race condition: the outcome depends on an order the program does not fix. Here an atomicity violation: the deposit is split across a suspension point.
A linearization point of a call: an instant between the call and its return at which it takes effect. No choice of one for each deposit gives 120.
deposit(10) reads the balance: b is 100.
At the await it is suspended; the script goes on.
const approve = n => new Promise(res =>
setTimeout(res, 100));new Promise(res => …) makes a pending promise and hands us res: calling res(v) fulfills it with v. Here a timer calls res after 100 ms.
deposit(20) reads the balance: still 100.
It is suspended too. Both approvals are pending.
const approve = n => new Promise(res =>
setTimeout(res, 100));The first approval arrives: deposit(10) writes 110.
The second: deposit(20) writes 100 + 20 = 120.
Not a data race: no two accesses are ever concurrent on one thread. Rust’s compiler and Go’s race detector look for data races: locking the read and the write separately passes both, and a deposit is still lost.
The repair: what was assumed before the await is re-established after it. Read after the wait: the read and the write are one atomic stretch, where the deposit takes effect. 130 in both orders.
await, can.awaitEach one is run in the demo, step by step, on the model’s parts: our code, the runtime, the host.
awaitfetchUser answers with "Ada" after 300 ms: a request to a server, imitated by a timer, which calls res("Ada") and so fulfills the promise.
What is printed, in which order?
load up to its first await and returns; the script prints B; when the value arrives, the rest of load prints C Ada.await load(); instead, the script is suspended too, and prints B last: A, C Ada, B.loadstep by step, on the model’s four partsload prints A, awaits a user that arrives after 300 ms, and prints C with the name. The script prints B.
Property 1: suspended only at the await; the caller continues. A, B, C Ada.
Our code in front; behind it, the runtime: the stack, the heap, the queues, the loop; at the back, the host.
get answers after 300 ms. In together, both requests have left before either is awaited.
How long does each function take?
inTurn 600 ms, together 300 mstogether overlap, 300 ms. In inTurn the request for b leaves only after a has arrived: 600 ms.await leaves after it. Start the work first, then await.Two values, a and b, each 300 ms away. inTurn awaits a, then asks for b; together asks for both first.
Property 2: the waits overlap, the running stretches never do. 600 against 300 ms.
Two values, a and b, each 300 ms away in the host. First inTurn.
A timer due at 100 ms, then a loop that computes for 500 ms without reaching a suspension point.
When does tick print?
done at 500 ms, then tick.A timer of 100 ms, then a loop that computes for 500 ms without an await.
Property 3: running code keeps the thread until it returns. done at 500 ms, then tick.
The loop takes the next function only when the stack is empty; this script empties it only by returning.
approve answers after 100 ms. Required: 130 when both calls have finished.
What is the balance then?
Two deposits on one balance, 10 and 20, each suspended at its approval. Required: 130.
Property 4 ends at the await: the read and the write are two stretches, and the other call runs between them. 120.
One thread runs our code. The balance is 100. We call deposit(10), then deposit(20).
await on a finished resultcreate_task queues the work: B, A, C Ada. An await on a finished result goes straight on: 130; sleep(0) suspends: 120.Properties 1 to 4 describe JavaScript. Four questions, each decided by a small run or by the language’s interface, locate any other language with respect to them.
First: when does an asynchronous function start to run? At the call, or only when a scheduler takes it? The run: load(), then console.log("B").
| language | a call |
|---|---|
| JavaScript, C# | runs it up to its first await: A, B, C Ada |
| Python | a coroutine object, nothing runs: a warning, then B; create_task: B, A, C Ada |
| Rust | builds a future, which runs when polled |
| Kotlin | a suspend call waits: A, C Ada, B; launch queues it |
| Go, Java | a plain call waits: A, C Ada, B; with go or a virtual thread: B, A, C Ada in these runs, A and B in no fixed order |
await. In Python and Rust the call builds an object and runs nothing, session 5’s thunk usable once: await runs it in place, create_task or spawn queues it.await, or only when the value is missingSecond: what does an await do when the value is already there? Suspend anyway, so that every await is an interleaving point; or go straight on, so that the stretch stays atomic.
The run: the two deposits, with an approve that has nothing to wait for. In JavaScript, await null awaits a value already there; in Python, asyncio.sleep(0) asks for a wait of zero seconds.
| language | an await on a finished result |
|---|---|
| JavaScript | suspends, even await null: 120 |
| Python | goes straight on: 130; await sleep(0) suspends: 120 |
| C#, Rust, Kotlin | goes straight on |
| Go, Java | there is no await |
await. Elsewhere an await on a value already there is not a suspension point: on one thread, the stretch around it stays atomic.Third: which thread resumes a suspended computation? The one thread of the loop, as the model assumes; or any thread of a pool.
The run: the two deposits, with a real wait, on the runtime each language gives by default.
| language | the thread that resumes |
|---|---|
| JavaScript | the one thread: always 120 |
| Python | the loop’s one thread: always 120 |
| C# | in a console program, a thread of a pool: 110 or 120 in these runs |
| Rust, Kotlin | the executor’s or the dispatcher’s choice |
| Go, Java | several threads: 110 or 120 in these runs; 130 possible |
then, and what other languages haveFourth: how is the rest of a function handed to the result it waits for? A call registers it on the result, as p.then(k) does; or a scheduler asks the result whether it is ready.
Before await, this was all we had. Each language reached it from a different start.
| language | the rest, handed over |
|---|---|
| JavaScript | then; before 2015, a callback |
| C# | ContinueWith; Wait blocks |
| Java | thenApply; get blocks |
| Python | add_done_callback |
| Kotlin | a Continuation, from the compiler |
| Rust | none: the executor polls the future |
await, the compiler writes the registration for us.| 1 | Suspended only at an await in it; after load(); the caller goes on, after await load(); it waits. |
| 2 | Waits overlap; on one thread, running never does. |
| 3 | Run-to-completion: running code keeps the thread until it returns. |
| 4 | A stretch with no await is atomic. The race on one thread is an atomicity violation, not a data race. |
the language guaranteesatomicity between suspension points, given one thread
a library givescombinators over promises: Promise.all, gather
the programmer keepsevery invariant that must survive a wait
Left open: what the kept rest of a function is; who holds it while the function waits; who invokes it, and when. The lab’s optional quest.
appendix| lab | The warm-up: the two blocks of today, on JavaScript with Python beside it. The optional quest: a small page on continuations, with exercises on paper; the appendix of this deck is its reading. |
| 7 | Several threads on one memory. The repaired deposit, run by two Java threads twenty thousand times: 130 in about 98 runs of 100, 110 or 120 in the others. The suspension points are gone, and with them the atomic stretch. |
Definition. The continuation of a point in a computation is the rest of the computation from that point, as a function of the value expected there.
In double(x) + 1, while double(x) is computed, the rest is the context [·] + 1: the function v => v + 1. At the await of load, the rest is user => { console.log("C", user); }.
// doubleK asks a server for 2x; the answer goes to k, 100 ms later
const doubleK = (x, k) => setTimeout(() => k(2 * x), 100);
const f = x => double(x) + 1; // double cannot return: write fK
JavaScriptconst fK = (x, k) => doubleK(x, v => k(v + 1)); // A
const fK = (x, k) => doubleK(x, k) + 1; // B
const fK = (x, k) => k(doubleK(x) + 1); // CThe cost: every function that needs the result of fK for its own result takes a continuation too, up the chain of calls. Hence async on every function that uses await, and on every caller that awaits its result.
JavaScript
resolve has the waiting continuations. Call each of them now, inside resolve, or put each in the queue for the loop?
JavaScript
JavaScript queues: a function given to then is never called before the current code has run to completion (Promises/A+, 2.2.4). Property 3 is these lines. Property 4 is kept by then and resolve calling later instead of k.
g.next(v) makes v the value of the yield where g was suspended.
A wait inside a loop: the generator’s object keeps i and the position.
async function as a generator and a driverawait became yieldA, B, C Ada on our promise, our queue, our loop and our driver: what the language did.
drive makes g and calls step, which calls g.next(): load runs on the stack and prints A.
back| language | a call | an await on a finished result | the thread that resumes | who keeps the suspended state |
|---|---|---|---|---|
| JavaScript | runs to the first await | suspends | the one thread | the compiler (stackless) |
| C# | goes straight on | a thread of a pool (console) | ||
| Python (asyncio) | builds a coroutine object | the loop’s one thread | ||
| Rust | builds a future | the executor’s choice | ||
| Kotlin | a suspend call waits; launch queues | the dispatcher’s choice | ||
| Go, Java (virtual threads) | a call waits; go or a virtual thread starts it apart | no await | several threads | the runtime (stackful) |
| OCaml 5 (effects) | runs until it performs an effect | one domain; a scheduler in a library (not run) |
main.mjsimport { Worker } from "node:worker_threads";
const t0 = Date.now(), ms = () => Date.now() - t0;
const w = new Worker(
new URL("./fib.mjs", import.meta.url));
w.on("message", () => {
console.log("fib(40) at", ms(), "ms");
w.terminate();
});
w.postMessage(40);
setTimeout(() =>
console.log("tick at", ms(), "ms"), 100);
fib.mjsimport { parentPort } from "node:worker_threads";
const fib = n =>
n < 2 ? n : fib(n - 1) + fib(n - 2);
parentPort.on("message", n =>
parentPort.postMessage(fib(n)));
A worker is another thread with its own loop: its own stack, heap and queue.
The two threads share no object. postMessage sends a copy; it arrives as a function in the other thread’s queue.
The tick is on time: the computation runs on the worker’s thread. On one thread it came at 504 ms.
SharedArrayBuffer, memory both threads write; with it, data races return: session 7.The read moves after the await. The read and the write are then one stretch with no await: atomic, by Property 4.
Each deposit takes effect in that stretch. 130, whichever approval arrives first.
await is re-established after it.| the callee calls it | with a callback | with a promise |
|---|---|---|
| twice | the rest runs twice | settled once: a second res does nothing |
| now or later | the order of our lines depends on it | what waits always goes to the queue |
| never | it waits for ever, silently | the same |
The cached userK of the callbacks slide, wrapped in a promise: B first, on a miss and on a hit.