mirror of
https://github.com/vercel-labs/scriptc.git
synced 2026-10-28 06:53:42 +08:00
A worker message round trip cost about 12 µs, almost all of it in two blocked waits: the poster signaled the waiting thread while it still held the mailbox lock, so the woken thread went back to sleep on the lock, and every wait paid a sleep and a wakeup. scr_mailbox_post and close now signal after the unlock, and scr_mailbox_wait spins for up to 20 µs (or the wait's timeout, if shorter) on a flag the queue keeps before it blocks. A process that may run on only one CPU never spins. A new bench:runtime workload, worker-messages, posts 100,000 round trips between the main thread and a worker: 1296 -> 360 ms.
25 lines
857 B
TypeScript
25 lines
857 B
TypeScript
// Message round trips between the main thread and one worker: the main
|
|
// thread posts a number and the worker answers it plus one, the given
|
|
// number of times. Each round trip is two messages and two wakeups of a
|
|
// waiting thread. Argument: the number of round trips.
|
|
import { Worker, isMainThread, parentPort } from "node:worker_threads";
|
|
|
|
if (isMainThread) {
|
|
const rounds = Number(process.argv[2] ?? "100000");
|
|
const worker = new Worker(new URL(import.meta.url));
|
|
let sent = 0;
|
|
let sum = 0;
|
|
worker.on("message", (value: number) => {
|
|
sum += value;
|
|
if (++sent === rounds) {
|
|
console.log(`${rounds} round trips, sum ${sum}`);
|
|
void worker.terminate();
|
|
} else worker.postMessage(sent);
|
|
});
|
|
worker.postMessage(0);
|
|
} else {
|
|
parentPort!.on("message", (value: number) => {
|
|
parentPort!.postMessage(value + 1);
|
|
});
|
|
}
|