PROGRAMMING PARADIGMS · PART 2 · SESSION 6, BLOCK 2

Asynchronous programming

concurrency on one thread

What does a program do while it waits, and where is the rest of a function while it waits?

PART 1

The model and its properties

one thread, four properties

The modelone thread, a stack, a heap, a queue, and a host

our code async function load() { console.log("A"); const user = await fetchUser(); console.log("C", user); } load(); console.log("B"); the runtime, one thread stack heap queue loop takes one function,runs it to its end the host clocknetworkdisk

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.

Suspension pointscooperative transfer of control

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.

running suspended ready await the value arrives the loop takes it, when the stack is empty a call

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.

Creating and awaiting a promisenew Promise and await†

new Promise(executor): making and settling

const fetchUser = () =>
  new Promise(res =>
    setTimeout(() => res("Ada"), 300));
  1. It creates a pending promise in the heap.
  2. It calls executor at once, with res.
  3. Later, whoever holds res calls res(v), and the promise becomes fulfilled with v.

await e: waiting and resuming

const user = await fetchUser();
  1. It evaluates e. If the result is not a promise, it is wrapped into an already fulfilled one.
  2. It registers the rest of the function on that promise, as one of its waiters: await p amounts to p.then(rest)*.
  3. It suspends the function: its frame leaves the stack, and its caller goes on.
  4. When the promise is fulfilled, the rest goes to the microtask queue; the loop runs it, and await e has the promise’s value.
the runtime, one thread stack heap queue loop the host script load() fetchUser() promise ppending promise pfulfilled timer() => res(…) rest of load()waits on p () => res(…) () => res(…) rest of load()ready load() resumed

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.

appendix

Callbacksthe rest of a computation, passed by hand

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.

  1. Nesting: each step is written inside the callback of the step before. With await, the steps follow one another.
  2. No composition: a result not yet arrived is not a value; waiting for two takes a counter. A promise is a value: stored, passed on, awaited by several.
  3. Inversion of control: the function we call decides when our callback runs, and how many times. A promise is settled once, and what waits on it always goes to the queue.
  4. Errors: an exception thrown in a callback does not reach the caller’s 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.

appendix

Run-to-completionthe loop’s rule, and two consequences

a and b: two requests, each answered after 300 ms; made in turn, or together before either is awaited.

in turn a b 600 ms together a b 300 ms running waiting the two waits overlap in time running: one at a time, each to its end

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.

appendix

Interleavings and atomicitywhere one computation can run inside another

P’s value arrives first P Q P’s value Q’s value Q’s value arrives first P Q Q’s value P’s value a suspension point:the only place anothercomputation can run a stretch with no await:atomic for every othercomputation running waiting

Execution: 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.

The race on one threada read, a suspension point, a write

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) b = 100 balance = 110110 deposit(20) b = 100 balance = 120120 balance 100

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.

A lock? A thread’s lock cannot help: there is one thread, and holding it across the wait blocks it.
An asynchronous lock, acquired with await, can.
appendix
PART 2

Worked examples

the programs of part 1, run on the stage
  1. One await
  2. Two requests of 300 ms
  3. A timer and a computation
  4. Two deposits

Each one is run in the demo, step by step, on the model’s parts: our code, the runtime, the host.

Example 1: one await

fetchUser 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?

  1. A, B, C Ada
  2. A, C Ada, B
  3. B, A, C Ada
Property 1: the call runs load up to its first await and returns; the script prints B; when the value arrives, the rest of load prints C Ada.
With await load(); instead, the script is suspended too, and prints B last: A, C Ada, B.

Demo 1: the run of loadstep by step, on the model’s four parts

load 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.

i

Our code in front; behind it, the runtime: the stack, the heap, the queues, the loop; at the back, the host.

Example 2: two requests of 300 ms

get answers after 300 ms. In together, both requests have left before either is awaited.

How long does each function take?

  1. 300 ms each
  2. inTurn 600 ms, together 300 ms
  3. 600 ms each

    
Property 2: the two waits of together overlap, 300 ms. In inTurn the request for b leaves only after a has arrived: 600 ms.
The text decides: a request written after an await leaves after it. Start the work first, then await.

Demo 2: two requestsin turn, then together

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.

i

Two values, a and b, each 300 ms away in the host. First inTurn.

Example 3: a timer and a computation

A timer due at 100 ms, then a loop that computes for 500 ms without reaching a suspension point.

When does tick print?

  1. at 100 ms
  2. at about 500 ms
  3. never
Property 3: the timer’s function is in the queue from 100 ms; the loop takes it only when the running code has returned. done at 500 ms, then tick.
Keeping the thread free is our job: split the computation, or move it to another thread, a worker.

Demo 3: a timer and a computation

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.

i

The loop takes the next function only when the stack is empty; this script empties it only by returning.

Example 4: two deposits

JavaScript

approve answers after 100 ms. Required: 130 when both calls have finished.

What is the balance then?

  1. 130
  2. 120
  3. 110
Both calls read 100 before either writes; the second write overwrites the first: 120. With the first approval slower, 110. In both orders a deposit is lost.
It happens wherever we read shared state, wait, then write it:
a counter updated after a request, a cache refreshed after a fetch.

Demo 4: two depositsequal approvals; then the first one slower

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.

i

One thread runs our code. The balance is 100. We call deposit(10), then deposit(20).

PART 3

Other languages

the same programs, against the model

The same programs in Pythona bare call; an await on a finished result

Does a call start the work?

Is every await a suspension point?

A bare call runs nothing; Python warns. create_task queues the work: B, A, C Ada. An await on a finished result goes straight on: 130; sleep(0) suspends: 120.
A coroutine object that is never awaited never runs:
its work is lost, and the warning is the only sign of it.

Starting the workat the call, or later

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").

languagea call
JavaScript, C#runs it up to its first await: A, B, C Ada
Pythona coroutine object, nothing runs: a warning, then B; create_task: B, A, C Ada
Rustbuilds a future, which runs when polled
Kotlina suspend call waits: A, C Ada, B; launch queues it
Go, Javaa 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
Two realizations of one model. In JavaScript and C# the call runs the function to its first 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.

The suspension pointat every await, or only when the value is missing

Second: 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.

languagean await on a finished result
JavaScriptsuspends, even await null: 120
Pythongoes straight on: 130; await sleep(0) suspends: 120
C#, Rust, Kotlingoes straight on
Go, Javathere is no await
Of these languages only JavaScript suspends at every await. Elsewhere an await on a value already there is not a suspension point: on one thread, the stretch around it stays atomic.

The resuming threadone thread, or a pool

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.

languagethe thread that resumes
JavaScriptthe one thread: always 120
Pythonthe loop’s one thread: always 120
C#in a console program, a thread of a pool: 110 or 120 in these runs
Rust, Kotlinthe executor’s or the dispatcher’s choice
Go, Javaseveral threads: 110 or 120 in these runs; 130 possible
Where a pool resumes the computations, two of them run at the same time: the model’s first assumption is gone, and Property 4 with it, although every suspension point is written. Session 7.

Registering the restthen, and what other languages have

Fourth: 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.

languagethe rest, handed over
JavaScriptthen; before 2015, a callback
C#ContinueWith; Wait blocks
JavathenApply; get blocks
Pythonadd_done_callback
Kotlina Continuation, from the compiler
Rustnone: the executor polls the future
JavaScript could not block its one thread: passing the rest was the only way to wait. Languages with threads could block first, and added this later. With await, the compiler writes the registration for us.
PART 4

Conclusion

the four properties; what is left open; the lab, and session 7

Conclusion of block 2

1Suspended only at an await in it; after load(); the caller goes on, after await load(); it waits.
2Waits overlap; on one thread, running never does.
3Run-to-completion: running code keeps the thread until it returns.
4A 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

Nextthe lab, and session 7

labThe 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.
7Several 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.
APPENDIX

The suspended computation as a value

continuations, a promise, a loop, a generator and a driver

Continuationsthe kept rest, written by hand

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); }.

back

Continuation-passing stylea function that cannot return takes its continuation

// 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);           // C

The 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.

back

A promise by handa write-once cell that holds continuations

JavaScript
A promise nobody resolves: its waiters never run.

If nothing can reach it any more, the collector frees it with them, silently. If something still can, they stay for ever: a memory leak.

resolve has the waiting continuations. Call each of them now, inside resolve, or put each in the queue for the loop?

back

The queue and the loopthe scheduler

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.

back

A value sent into a generatorsession 5’s object, resumed with a value

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.

back

An async function as a generator and a driverawait became yield

A, B, C Ada on our promise, our queue, our loop and our driver: what the language did.

i

drive makes g and calls step, which calls g.next(): load runs on the stack and prints A.

back

Languages against the modeltask management and stack management

languagea callan await on a finished resultthe thread that resumeswho keeps the suspended state
JavaScriptruns to the first awaitsuspendsthe one threadthe compiler (stackless)
C#goes straight ona thread of a pool (console)
Python (asyncio)builds a coroutine objectthe loop’s one thread
Rustbuilds a futurethe executor’s choice
Kotlina suspend call waits; launch queuesthe dispatcher’s choice
Go, Java (virtual threads)a call waits; go or a virtual thread starts it apartno awaitseveral threadsthe runtime (stackful)
OCaml 5 (effects)runs until it performs an effectone domain; a scheduler in a library (not run)
Task management: who may run between two of our lines. Stack management: who keeps the suspended state. Two independent questions (Adya et al., 2002).
back

Worker threadsanother thread, another loop

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.

On each thread, Properties 1 to 4 hold; between threads, messages: session 8. The exception is a SharedArrayBuffer, memory both threads write; with it, data races return: session 7.
back

The repairthe read after the wait

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.

What was assumed before an await is re-established after it.
back

Inversion of controlwhat a promise rules out

the callee calls itwith a callbackwith a promise
twicethe rest runs twicesettled once: a second res does nothing
now or laterthe order of our lines depends on itwhat waits always goes to the queue
neverit waits for ever, silentlythe same

The cached userK of the callbacks slide, wrapped in a promise: B first, on a miss and on a hit.

The first two are ruled out by the promise’s two rules. The third is a liveness failure: no finite run shows it.
back