Offload functions to worker threads with shared memory primitives for Node.js.
1// Multiple workers updating shared struct state protected by a mutex.
2// Without the mutex, the read-modify-write would race and lose updates.
3// Requires Node v24+.
4//
5// Run: node examples/shared-state/main.ts
6
7import { workers, shared, int32, mutex } from '../../src/index.ts';
8import { updatePosition } from './update-position.ts';
9
10const mu = mutex();
11const pos = shared({ x: int32, y: int32 });
12
13const steps = 1000;
14
15{
16 using run = workers(4);
17
18 // 4 workers each move the position (1, 2) per step, 1000 steps each
19 await run([
20 updatePosition(mu, pos, 1, 2, steps),
21 updatePosition(mu, pos, 1, 2, steps),
22 updatePosition(mu, pos, 1, 2, steps),
23 updatePosition(mu, pos, 1, 2, steps),
24 ]);
25}
26
27const final = pos.load();
28console.log(`Expected: { x: ${4 * steps}, y: ${4 * steps * 2} }`);
29console.log(`Actual: { x: ${final.x}, y: ${final.y} }`);
30console.log(final.x === 4 * steps && final.y === 4 * steps * 2 ? 'PASS — mutex prevented races' : 'FAIL — data race!');