Skip to content

Commit fa77dc5

Browse files
addaleaxBridgeAR
authored andcommitted
worker: make terminate() resolve for unref’ed Workers
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 <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]>
1 parent 79a277e commit fa77dc5

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

lib/internal/worker.js

+2
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,8 @@ class Worker extends EventEmitter {
226226
terminate(callback) {
227227
debug(`[${threadId}] terminates Worker with ID ${this.threadId}`);
228228

229+
this.ref();
230+
229231
if (typeof callback === 'function') {
230232
process.emitWarning(
231233
'Passing a callback to worker.terminate() is deprecated. ' +
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
'use strict';
2+
const common = require('../common');
3+
const { once } = require('events');
4+
const { Worker } = require('worker_threads');
5+
6+
// Test that calling worker.terminate() on an unref()’ed Worker instance
7+
// still resolves the returned Promise.
8+
9+
async function test() {
10+
const worker = new Worker('setTimeout(() => {}, 1000000);', { eval: true });
11+
await once(worker, 'online');
12+
worker.unref();
13+
await worker.terminate();
14+
}
15+
16+
test().then(common.mustCall());

0 commit comments

Comments
 (0)