// Multiple workers updating shared struct state protected by a mutex. // Without the mutex, the read-modify-write would race and lose updates. // Requires Node v24+. // // Run: node examples/shared-state/main.ts import { workers, shared, int32, mutex } from '../../src/index.ts'; import { updatePosition } from './update-position.ts'; const mu = mutex(); const pos = shared({ x: int32, y: int32 }); const steps = 1000; { using run = workers(4); // 4 workers each move the position (1, 2) per step, 1000 steps each await run([ updatePosition(mu, pos, 1, 2, steps), updatePosition(mu, pos, 1, 2, steps), updatePosition(mu, pos, 1, 2, steps), updatePosition(mu, pos, 1, 2, steps), ]); } const final = pos.load(); console.log(`Expected: { x: ${4 * steps}, y: ${4 * steps * 2} }`); console.log(`Actual: { x: ${final.x}, y: ${final.y} }`); console.log(final.x === 4 * steps && final.y === 4 * steps * 2 ? 'PASS — mutex prevented races' : 'FAIL — data race!');