The lab follows the two blocks of the lecture: block 1, the introduction to Part 2, and block 2, asynchronous programming (concurrency on one thread).
The warm-up is the main part of the lab, and we finish it during the lab session. It has three questions on paper on the introduction; six programs in JavaScript, five to predict and one to repair; three questions in Python, on two programs, to predict; and a last program in JavaScript, on its two queues. We write each prediction down before we run the program. The quest is optional: five short exercises on continuations. They go with the appendix of block 2, The suspended computation as a value, which we read first. Nothing is handed in.
We need node and python3. The programs are in warmup/js/, warmup/py/ and quest/. The sheet warmup/warmup.pdf has the same questions as the warm-up on this page.
Warm-up
Part 1: Correctness and coordinationon paper
Three questions on the introduction. We write the answers on a page of our own.
Question 1
Given the five requirements of the bank account below, say of each whether it is a safety property or a liveness property.
no deposit answered ok is lost;
no request changes the balance twice;
the balance is never negative;
every request gets a definitive answer in the end;
the two copies of the account, kept on two machines, agree in the end.
Question 2
A semaphore is a counter with two operations: acquire waits until the counter is above zero, then takes one off; release adds one. Given Dijkstra's bounded buffer in Java, as in the introduction, say for each of the three semaphores whether it expresses not before or not at the same time, and which action waits for which other action.
Java
Semaphore numberOfQueuingPortions = new Semaphore(0);
Semaphore numberOfEmptyPositions = new Semaphore(N); // N places
Semaphore bufferManipulation = new Semaphore(1);
// producerfor (int k = 1; k <= 8; k++) {
String portion = produceNextPortion(k);
numberOfEmptyPositions.acquire();
bufferManipulation.acquire();
buffer.addLast(portion);
bufferManipulation.release();
numberOfQueuingPortions.release();
}
// consumerfor (int k = 1; k <= 8; k++) {
numberOfQueuingPortions.acquire();
bufferManipulation.acquire();
String portion = buffer.removeFirst();
bufferManipulation.release();
numberOfEmptyPositions.release();
processPortionTaken(portion);
}
Question 3
Given the bank account with a balance of 100, where withdraw(n) answers refused when the balance would become negative, and two clients, A and B, that each call withdraw(80) at the same moment, so that the two calls overlap: for each of the two executions below, say whether its calls can be put in such a sequence, and if they can, give the sequence.
both calls answer ok;
A's call answers ok, B's call answers refused.
Part 2: Asynchronous functions in JavaScriptpredict on paper, then run
We read each program, choose one of the three answers, and write it down. Then we run the program in warmup/js/, for example node q4_two_loads.mjs. Where the run differs from our answer, we find the property that explains it. In question 9 we write a function, then run it.
Question 4
Given the program below, what does it print, in which order?
JavaScriptwarmup/js/q4_two_loads.mjs
// Question 4. Run: node q4_two_loads.mjs// fetchUser answers "Ada" after 300 ms: a request, imitated by a timerconst fetchUser = () => new Promise(res => setTimeout(() => res("Ada"), 300));
asyncfunction load(who) {
console.log("A", who);
const user = await fetchUser();
console.log("C", who, user);
}
load(1);
load(2);
console.log("B");
A 1, C 1 Ada, A 2, C 2 Ada, B
A 1, A 2, B, C 1 Ada, C 2 Ada
B, A 1, A 2, C 1 Ada, C 2 Ada
Question 5
Given the program below, in which the await is forgotten, what does it print, in which order?
JavaScriptwarmup/js/q5_forgotten.mjs
// Question 5. Run: node q5_forgotten.mjs// fetchUser answers "Ada" after 300 ms: a request, imitated by a timerconst fetchUser = () => new Promise(res => setTimeout(() => res("Ada"), 300));
asyncfunction load() {
console.log("A");
const user = fetchUser(); // the await is forgotten
console.log("C", user);
}
load();
console.log("B");
A, B, C Ada
A, C Ada, B
A, C Promise { <pending> }, B
Question 6
Given the program below, what does it print, and at which times?
JavaScriptwarmup/js/q6_two_requests.mjs
// Question 6. Run: node q6_two_requests.mjs// get(name, ms) answers name after ms milliseconds: a request, imitated by// a timerconst get = (name, ms) => new Promise(res => setTimeout(() => res(name), ms));
const t0 = Date.now();
// now(): the time since the start, to the nearest 100 msconst now = () => Math.round((Date.now() - t0) / 100) * 100 + " ms";
asyncfunction main() {
const pa = get("a", 300);
const pb = get("b", 100); // both requests have left
console.log(await pa, "at", now());
console.log(await pb, "at", now());
}
main();
b at 100 ms, then a at 300 ms
a at 300 ms, then b at 300 ms
a at 300 ms, then b at 400 ms
Question 7
Given the program below, in which f awaits a value that is already there, what does it print, in which order?
Given the program below, in which each deposit is one line, balance += await amount(n), what does it print? In JavaScript, balance += e reads balance first, then evaluates e, then writes the sum.
JavaScriptwarmup/js/q8_plus_await.mjs
// Question 8. Run: node q8_plus_await.mjs// amount(n) answers n after 100 ms: a request, imitated by a timerconst amount = n => new Promise(res => setTimeout(() => res(n), 100));
let balance = 100;
asyncfunction deposit(n) {
balance += await amount(n);
}
// wait until both calls have finished, then print the balanceawait Promise.all([deposit(10), deposit(20)]);
console.log(balance);
130
120
110
Question 9
Given the deposit of the lecture, which reads the balance, waits for an approval, and writes the new balance, write depositRepaired in warmup/js/q9_deposits.mjs, in place of todo(9). The repaired deposit still waits for the approval before it changes the balance. Two deposits, of 10 and 20, give 130, whatever the order of their approvals. Then we run node q9_deposits.mjs. It prints the balance after the two deposits, in both orders: first for the deposit of the lecture, then for the repaired one.
JavaScriptwarmup/js/q9_deposits.mjs
// the deposit of the lecture: read, wait, writeasyncfunction deposit(account, n, ms) {
const b = account.balance;
await approve(n, ms);
account.balance = b + n;
}
// the same deposit, repaired: it must give 130 in both ordersasyncfunction depositRepaired(account, n, ms) {
todo(9);
}
The check: the last two lines, repaired, equal approvals and repaired, first approval slower, each end in 130.
Part 3: Asynchronous functions in Pythonpredict on paper, then run
The lecture asked three questions of every language. Here we ask Python the first two: does a call start the work, and is every await a suspension point? In JavaScript the answers are yes and yes (questions 4 and 7). The third question, which thread resumes a suspended computation, has the same answer in both languages: the loop's one thread. The programs are in warmup/py/.
Question 10
Given the program below, what does python3 q10_load.py bare print?
a warning that the coroutine load was never awaited, then B
A, C Ada, B
Question 11
Given the same program, what does python3 q10_load.py task print?
A, B, C Ada
B, A, C Ada
B only
Question 12
Given the deposit of the lecture in Python, and a program that runs the two deposits twice, first with an approve() that has nothing to wait for, then with one that waits for 0 seconds, what does python3 q12_deposits.py print?
Pythonwarmup/py/q12_deposits.py
# Question 12. Run: python3 q12_deposits.pyimport asyncio
asyncdef nothing_to_wait_for():
passasyncdef really_waits():
await asyncio.sleep(0)
asyncdef trial(name, approve):
account = {"balance": 100}
asyncdef deposit(n):
b = account["balance"]
await approve()
account["balance"] = b + n
await asyncio.gather(deposit(10), deposit(20))
print(f"{name:36}", account["balance"])
asyncio.run(trial("approve() has nothing to wait for", nothing_to_wait_for))
asyncio.run(trial("approve() waits, for 0 seconds", really_waits))
120, then 120
130, then 120
130, then 130
Part 4: Two queues in JavaScriptpredict on paper, then run
The model of the lecture has one queue. JavaScript has two, and one program shows the difference. The program is in warmup/js/.
Question 13
Given the program below, with a timer of 0 ms and a promise that is already fulfilled, what does it print, in which order?
The quest is optional. It goes with the appendix of block 2, The suspended computation as a value, which we read first: continuations, continuation-passing style, a promise by hand, the queue and the loop, a value sent into a generator, an async function as a generator and a driver.
We do each exercise on paper first, then write it in its file in quest/, and check it with node checks.mjs. The checks print one line each: pass, FAIL, or todo for an exercise not written yet. A hole is marked todo(n): it throws an error, TODO n, until we write the code in its place. Exercise 2 uses gK of exercise 1; exercises 4 and 5 use resolve of exercise 3. Until exercise 3 is written, node trace.mjs prints A, B, D and then stops with Error: TODO 3. node load.mjs stops with Error: TODO 5 until exercise 5 is written, and with Error: TODO 3 until exercise 3 is.
Exercise 1
Given tripleK, which asks a server for 3 * x and calls k with the answer 100 ms later, and the function g = x => triple(x) - 1, where triple(x) stands for the server's answer: write gK, the form of g in continuation-passing style, in cps.mjs.
JavaScriptquest/cps.mjs
// tripleK(x, k): asks a server for 3 * x; the answer goes to k, 100 ms laterexportconst tripleK = (x, k) => setTimeout(() => k(3 * x), 100);
// gK(x, k): gives k the value of g(x), where g = x => triple(x) - 1// and triple(x) is 3 * x, the answer of the serverexportconst gK = (x, k) => todo(1);
The check:gK(2, k) gives k the value 5, 100 ms later.
Exercise 2
Given gK, and the function h = x => g(g(x)), write hK in cps.mjs.
JavaScriptquest/cps.mjs
// hK(x, k): gives k the value of h(x), where h = x => g(g(x))exportconst hK = (x, k) => todo(2);
The check:hK(2, k) gives k the value 14, about 200 ms later: two replies, one after the other.
Exercise 3
Given the class P, a promise, with then written, and later(k), which puts k in the queue, write resolve(v) in ours.mjs. If the promise is still pending, resolve(v) sets its state to "fulfilled" and its value to v, and puts each continuation of waiters in the queue, to be called with v. If the promise already has a value, resolve does nothing. We write it from this description, then compare it with the appendix's slide A promise by hand.
JavaScriptquest/ours.mjs
// a promise: a value not there yet, and the continuations that wait for itexportclass P {
state = "pending"; value; waiters = [];
// then(k): registers k, the continuation that waits for the value
then(k) {
if (this.state === "pending") this.waiters.push(k);
else later(() => k(this.value));
}
// resolve(v): if pending, stores v; puts each waiter in the queue, with v
resolve(v) {
todo(3);
}
}
The check:const p = new P(); p.then(v => console.log("k " + v)); p.resolve(1); console.log("after resolve") prints after resolve, then k 1, as in the appendix's slide The queue and the loop.
Exercise 4
Given later, run and P of ours.mjs, with resolve written, and the program trace.mjs below, we fill in, on paper, a table with one row for each step. A step is one line of the script, one function that our loop takes from ready, or the host's timer function that resolves p; one more row is for the moment the script has returned. We call k the function user => console.log("C", user) and d the function () => console.log("D"). The columns say what is running, what is in our queue ready (the host's timers are not in it), which continuations wait on p, and what has been printed so far. The table has nine rows. Then we run node trace.mjs.
JavaScriptquest/trace.mjs
// The quest, exercise 4: fill in the table on paper first, then run:// node trace.mjsimport { later, fetchUser } from"./ours.mjs";
const p = fetchUser();
console.log("A");
p.then(user => console.log("C", user));
later(() => console.log("D"));
console.log("B");
step
running
our queue ready
waiting on p
printed so far
1
the script: fetchUser() makes p; the host will resolve it in 300 ms
—
—
—
The first row is filled in. We add one row for each step, until the program has printed everything.
The check: the last column of the last row is what node trace.mjs prints.
Exercise 5
Given load written as a generator that yields the promises it waits for, write drive(gen) in ours.mjs. drive calls gen() to make the generator g, and runs it at once, up to its first yield. To each promise that g yields, drive gives, with then, the continuation that resumes g with the value. It stops when g is done. We write it from this description, then compare it with the appendix's slide An async function as a generator and a driver.
JavaScriptquest/load.mjs
function* load() {
console.log("A");
const user = yield fetchUser(); // await became yield
console.log("C", user);
}
drive(load);
console.log("B");
JavaScriptquest/ours.mjs
// drive(gen): runs the generator made by gen; each promise it yields is// given the continuation "resume the generator with the value"exportfunction drive(gen) {
todo(5);
}
The check:node checks.mjs runs a copy of load with drive, and node load.mjs prints A, B, C Ada, as the async function did.
Limits and further reading
What ours.mjs leaves out: then returns nothing, so continuations cannot be chained; there is no second continuation, for failure, as JavaScript's then(onFulfilled, onRejected) has; and the loop is started with a timer of the host, so it runs on top of JavaScript's own loop.
Lab 5's Part C is the same idea in OCaml: a continuation kept and called later, and two continuations, k and h. Reading: Leroy, Control structures in programming languages (2026), chapters 6 and 7.