Await Points Interleave Concurrent Tasks

Each await hands control back to the event loop, so concurrent tasks interleave and a read-modify-write spanning an await silently loses updates.

JavascriptData Integrity

Code

javascriptsnippet
27 lines
// every await yields control: concurrent tasks interleave as each one suspends
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const log = [];

async function worker(name, steps) {
  for (const step of steps) {
    log.push(name + ' start ' + step);
    await sleep(10); // suspension point: the other task advances here
    log.push(name + ' done ' + step);
  }
}

let counter = 0;
async function bump() {
  const current = counter; // read
  await sleep(5); // suspension: the other two bumps complete their reads in the meantime
  counter = current + 1; // writes back a stale value -> lost update
}

async function main() {
  await Promise.all([worker('A', [1, 2]), worker('B', [1, 2])]);
  console.log(log.join(' -> '));
  await Promise.all([bump(), bump(), bump()]);
  console.log('counter after 3 bumps:', counter, '(lost updates)');
}

main();

What the code does

Count the functions sleep, worker, bump and main as the entire surface area of Await Points Interleave Concurrent Tasks.

Iteration happens inside for (const step of steps) — everything outside it runs once. The asynchronous flow is linearized with await, keeping failure handling local.

Using it

The main signature reads const sleep = (ms)

Running the file prints labeled results such as counter after 3 bumps: — each operation’s effect is visible in the output.

main is the driver: it invokes worker and bump before returning.

Key statements

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await Promise.all([worker('A', [1, 2]), worker('B', [1, 2])]);
await Promise.all([bump(), bump(), bump()]);

Interactive Tools for This Topic

FAQ

What does Await Points Interleave Concurrent Tasks print when run?
Execute the whole file; each printed line is prefixed with a label like `counter after 3 bumps:`.