From d20cde8460b36578a4a7c1dedb3a8805f2e8bffa Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sun, 11 Feb 2024 16:25:16 +0100 Subject: [PATCH] fix: ensure `worker_threads` workers are unreferenced at termination MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- CHANGELOG.md | 4 ++++ src/pools/worker-node.ts | 1 + src/pools/worker.ts | 6 ++++++ 3 files changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab225e96..36a6bc50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- Ensure `worker_threads` workers are unreferenced at termination. + ## [3.1.19] - 2024-01-16 ### Fixed diff --git a/src/pools/worker-node.ts b/src/pools/worker-node.ts index 30821517..523036a5 100644 --- a/src/pools/worker-node.ts +++ b/src/pools/worker-node.ts @@ -137,6 +137,7 @@ export class WorkerNode this.removeAllListeners() switch (this.info.type) { case WorkerTypes.thread: + this.worker.unref?.() await this.worker.terminate?.() break case WorkerTypes.cluster: diff --git a/src/pools/worker.ts b/src/pools/worker.ts index 05f6606e..d4075483 100644 --- a/src/pools/worker.ts +++ b/src/pools/worker.ts @@ -235,6 +235,12 @@ export interface IWorker extends EventEmitter { * @param handler - The event handler. */ readonly once: (event: string, handler: EventHandler) => this + /** + * Calling `unref()` on a worker allows the thread to exit if this is the only + * active handle in the event system. If the worker is already `unref()`ed calling`unref()` again has no effect. + * @since v10.5.0 + */ + readonly unref?: () => void /** * Stop all JavaScript execution in the worker thread as soon as possible. * Returns a Promise for the exit code that is fulfilled when the `'exit' event` is emitted. -- 2.34.1