Skip to content

Commit

Permalink
worker: make terminate() resolve for unref’ed Workers
Browse files Browse the repository at this point in the history
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: #29484
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
  • Loading branch information
addaleax authored and BridgeAR committed Sep 25, 2019
1 parent 79a277e commit fa77dc5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/internal/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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. ' +
Expand Down
16 changes: 16 additions & 0 deletions test/parallel/test-worker-terminate-unrefed.js
Original file line number Diff line number Diff line change
@@ -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());

0 comments on commit fa77dc5

Please sign in to comment.