Worker threads in JavaScript
Real parallelism for CPU work, with messages between the threads.
import { Worker, isMainThread, parentPort, workerData }
from "node:worker_threads";
const source = `
import { parentPort, workerData } from "node:worker_threads";
let total = 0;
for (let i = 1; i <= workerData.limit; i += 1) total += i;
parentPort.postMessage(total);
`;
if (isMainThread) {
const worker = new Worker(new URL(`data:text/javascript,${source}`), {
workerData: { limit: 1000 },
});
worker.on("message", (total) => console.log("worker said", total));
worker.on("error", (error) => console.log("worker failed", error.message));
} else {
parentPort.postMessage(workerData);
}
How it works
- The worker runs a separate module with its own event loop.
workerDatapasses the input;postMessagereturns the result.- Use it for CPU work, not for IO, which is already concurrent.
Keywords and builtins used here
constelsefromifimport
The run, in numbers
- Lines
- 19
- Characters to type
- 587
- Tokens
- 110
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 60 seconds.
Step 3 of 3 in Crypto & processes, step 17 of 18 in Node.js.