Concurrency

Worker termination and bounded admission

A worker pool reuses a bounded number of workers to process tasks. It amortizes startup cost and makes concurrency limits explicit. A task deadline is separate from task cancellation: the caller stopping its wait does not automatically stop the worker. Define maximum workers, maximum queued tasks, per-task deadline and a result/error protocol. If the queue is full, reject or apply backpressure instead of allowing unlimited waiting. Cooperative cancellation requires the worker to check a cancellation signal or shared flag at safe points; a CPU-bound loop cannot process ordinary cancellation messages until it yields. `worker.terminate()` stops a worker and is asynchronous; use it for an abandoned dedicated worker or replace a terminated pool worker. Termination can interrupt work, so it is not a graceful transaction rollback. Track cleanups and settle every pending promise exactly once. Do not implement timeouts only with Promise.race and forget the active worker. Do not silently drop tasks on shutdown or recreate failed workers without a restart budget. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/worker_threads.html.

Formal Syntax & Structure

nodejs syntaxnodejs
worker.terminate() returns Promise<number>

Working Example

Example Snippetnodejs
import {Worker} from 'node:worker_threads';import {once} from 'node:events';const worker=new Worker(new URL('./worker.mjs',import.meta.url));try {await once(worker,'message');console.log('ready');await worker.terminate();console.log('terminated');}finally{await worker.terminate();}
Node.js Reference