Offload functions to worker threads with shared memory primitives for Node.js.
8
fork

Configure Feed

Select the types of activity you want to include in your feed.

feat: add shared-state example using structs and mutex

Demonstrates multiple workers updating a shared struct position
protected by a mutex to prevent read-modify-write races.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

+45
+30
examples/shared-state/main.ts
··· 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 + 7 + import { pool, shared, int32, mutex } from '../../src/index.ts'; 8 + import { updatePosition } from './update-position.ts'; 9 + 10 + const lock = mutex(); 11 + const pos = shared({ x: int32, y: int32 }); 12 + 13 + const steps = 1000; 14 + 15 + { 16 + using run = pool(4); 17 + 18 + // 4 workers each move the position (1, 2) per step, 1000 steps each 19 + await Promise.all([ 20 + run(updatePosition(lock, pos, 1, 2, steps)), 21 + run(updatePosition(lock, pos, 1, 2, steps)), 22 + run(updatePosition(lock, pos, 1, 2, steps)), 23 + run(updatePosition(lock, pos, 1, 2, steps)), 24 + ]); 25 + } 26 + 27 + const final = pos.load(); 28 + console.log(`Expected: { x: ${4 * steps}, y: ${4 * steps * 2} }`); 29 + console.log(`Actual: { x: ${final.x}, y: ${final.y} }`); 30 + console.log(final.x === 4 * steps && final.y === 4 * steps * 2 ? 'PASS — mutex prevented races' : 'FAIL — data race!');
+15
examples/shared-state/update-position.ts
··· 1 + import { mo } from '../../src/index.ts'; 2 + import type { SharedStruct, Int32, Mutex } from '../../src/index.ts'; 3 + 4 + type Position = SharedStruct<{ x: Int32; y: Int32 }>; 5 + 6 + export const updatePosition = mo( 7 + import.meta, 8 + async (lock: Mutex, pos: Position, dx: number, dy: number, steps: number): Promise<void> => { 9 + for (let i = 0; i < steps; i++) { 10 + using guard = await lock.lock(); 11 + const current = pos.load(); 12 + pos.store({ x: current.x + dx, y: current.y + dy }); 13 + } 14 + }, 15 + );