Worker Thread Pool Scheduler
Hard · Async Patterns
CPU-heavy work in Node.js is moved to a pool of worker_threads (libraries like Piscina do this). Simulate how such a pool schedules tasks.
Write schedulePool(options, tasks). options is { workers, maxQueue? } and each task is { id, arrival, duration } (integers, duration >= 1). Workers are numbered from 0.
- A task that arrives while some worker is idle starts right away on the idle worker with the lowest index.
- If every worker is busy, the task joins the back of a FIFO queue. If the queue already holds maxQueue tasks, the task is rejected instead (no maxQueue means the queue is unlimited).
- When a worker finishes at time t, it immediately takes the task at the front of the queue (starting at t).
- At the same time t, handle things in this order: first all workers finishing at t (lowest index first), then tasks arriving at t (in input order).
Return { results, makespan }. results has one entry per task, in input order: { id, worker, start, end }, or { id, rejected: true }. makespan is the largest end (0 if nothing ran).