From fa77dc5f3b7a5dbe04098870b6315b9970e5f5a3 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 7 Sep 2019 21:56:24 +0200 Subject: [PATCH] =?UTF-8?q?worker:=20make=20terminate()=20resolve=20for=20?= =?UTF-8?q?unref=E2=80=99ed=20Workers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Once `worker.terminate()` is called, the Worker instance will be destroyed as soon as possible anyway, so in order to make the Promise returned by `worker.terminate()` resolve always, it should be okay to just call `.ref()` on it and keep the main event loop alive temporarily. PR-URL: https://github.com/nodejs/node/pull/29484 Reviewed-By: Ben Noordhuis Reviewed-By: Colin Ihrig Reviewed-By: Benjamin Gruenbaum --- lib/internal/worker.js | 2 ++ test/parallel/test-worker-terminate-unrefed.js | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 test/parallel/test-worker-terminate-unrefed.js diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 3cd5472b9341bd..df0646ff4f68b8 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -226,6 +226,8 @@ class Worker extends EventEmitter { terminate(callback) { debug(`[${threadId}] terminates Worker with ID ${this.threadId}`); + this.ref(); + if (typeof callback === 'function') { process.emitWarning( 'Passing a callback to worker.terminate() is deprecated. ' + diff --git a/test/parallel/test-worker-terminate-unrefed.js b/test/parallel/test-worker-terminate-unrefed.js new file mode 100644 index 00000000000000..adf6bbf14563cd --- /dev/null +++ b/test/parallel/test-worker-terminate-unrefed.js @@ -0,0 +1,16 @@ +'use strict'; +const common = require('../common'); +const { once } = require('events'); +const { Worker } = require('worker_threads'); + +// Test that calling worker.terminate() on an unref()’ed Worker instance +// still resolves the returned Promise. + +async function test() { + const worker = new Worker('setTimeout(() => {}, 1000000);', { eval: true }); + await once(worker, 'online'); + worker.unref(); + await worker.terminate(); +} + +test().then(common.mustCall());