Offload functions to worker threads with shared memory primitives for Node.js.
1import type { Balancer, WorkerHandle } from './runner.ts';
2
3/**
4 * Creates a round-robin balancer that cycles through workers in order.
5 * @returns A fresh Balancer instance.
6 */
7export function roundRobin(): Balancer {
8 let next = 0;
9 return {
10 select(workers: readonly WorkerHandle[]): WorkerHandle {
11 const worker = workers[next % workers.length];
12 next++;
13 return worker;
14 },
15 };
16}
17
18/**
19 * Creates a least-busy balancer that picks the worker with the lowest activeCount.
20 * Ties are broken by index (first wins).
21 * @returns A fresh Balancer instance.
22 */
23export function leastBusy(): Balancer {
24 return {
25 select(workers: readonly WorkerHandle[]): WorkerHandle {
26 let best = workers[0];
27 for (let i = 1; i < workers.length; i++) {
28 if (workers[i].activeCount < best.activeCount) {
29 best = workers[i];
30 }
31 }
32 return best;
33 },
34 };
35}