Sub topic 1
How JavaScript Runs Code in Parallel
JavaScript code runs on one thread at a time per agent. To use more than one CPU core, you start more agents and let them communicate. This chapter covers that model. The rest of the tutorial changes one part of it.
Prerequisites
This chapter assumes you know:
- Modern JavaScript syntax (ES2015+)
ArrayBufferand typed arrays such asInt32Array- The event loop and asynchronous code with Promises
- Basic use of Web Workers or Node.js
worker_threads
Agents and Their Event Loops
The specification calls an independent JavaScript execution context an agent. The browser main thread, each Web Worker, and each Node.js worker thread is a separate agent. Every agent has:
- Its own heap, which holds its objects
- Its own call stack
- Its own event loop and task queue
Inside one agent, code runs to completion. A function is never interrupted halfway through by other JavaScript in the same agent. That is why ordinary single-threaded JavaScript has no data races. Agents run in parallel with each other, on separate operating-system threads.
Message Passing: Copy or Transfer
Agents can't read each other's heaps. They communicate with postMessage, which delivers the data either as a copy or as a transfer:
| Mode | How | Effect on the sender |
|---|---|---|
| Structured clone | Default for most values | Sender keeps its original. The receiver gets a deep copy. |
| Transfer | List the object in the transfer list | Sender's object is detached and becomes unusable. |
Copying keeps the agents isolated, but copying large data costs time and memory. Transferring avoids the copy, but only one agent owns the data at any moment. Neither mode lets two agents work on the same bytes at the same time.
This Node.js script shows both modes:
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
const data = { count: 1 };
const buf = new ArrayBuffer(8);
worker.postMessage({ data, buf }, [buf]); // clone data, transfer buf
console.log('main buf:', buf.byteLength); // 0 (detached)
worker.on('message', (reply) => {
console.log('main data:', data.count); // 1 (original unchanged)
console.log('reply:', reply.count); // 2 (worker's copy)
worker.terminate();
});
} else {
parentPort.on('message', ({ data, buf }) => {
data.count++;
console.log('worker buf:', buf.byteLength); // 8
parentPort.postMessage(data);
});
}Common Mistakes
- Expecting a mutation to show up on the other side. The worker changed its own copy of
data, so the main thread'scountstayed1. - Using a buffer after you transfer it. After the transfer,
buf.byteLengthis0, and typed-array views on that buffer have no usable elements. - Trying to clone things that can't be cloned. Functions, DOM nodes, and class prototypes don't survive structured cloning. Sending a function throws a
DataCloneError.
Exercise
The main thread posts a 100 MB ArrayBuffer to a worker without listing it in the transfer list, then writes to it. Does the worker see the write, and what does the post cost?
Show answer
The worker does not see the write. Without a transfer list, the buffer is structured-cloned, so the worker gets its own 100 MB copy. That copy costs time and doubles memory use for that buffer. Transferring it would avoid the copy, but the main thread would lose access to the buffer.