Offload functions to worker threads with shared memory primitives for Node.js.
1// Demonstrates that the main thread event loop stays responsive
2// while heavy work runs on worker threads.
3// Requires Node v24+.
4//
5// Run: node examples/non-blocking/main.ts
6
7import { workers } from '../../src/index.ts';
8import { fibonacci } from './fibonacci.ts';
9
10// Tick a counter on the main thread to prove it's not blocked
11let ticks = 0;
12const interval = setInterval(() => {
13 ticks++;
14 process.stdout.write(`\r main thread tick #${ticks}`);
15}, 100);
16
17console.log('Computing fibonacci(42) on a worker pool...');
18console.log('Meanwhile, the main thread keeps ticking:\n');
19
20{
21 using run = workers(2);
22 const start = performance.now();
23 const [a, b] = await run([fibonacci(42), fibonacci(41)]);
24 const elapsed = (performance.now() - start).toFixed(0);
25
26 clearInterval(interval);
27 console.log(`\n\nResults: fib(42)=${a}, fib(41)=${b}`);
28 console.log(`Computed in ${elapsed}ms with ${ticks} main-thread ticks (not blocked!)`);
29}