diff --git a/test/parallel/test-worker-ref-onexit.js b/test/parallel/test-worker-ref-onexit.js new file mode 100644 index 00000000000000..0250c592ce91ae --- /dev/null +++ b/test/parallel/test-worker-ref-onexit.js @@ -0,0 +1,10 @@ +'use strict'; +const common = require('../common'); +const { Worker } = require('worker_threads'); + +// Check that worker.unref() makes the 'exit' event not be emitted, if it is +// the only thing we would otherwise be waiting for. + +const w = new Worker('', { eval: true }); +w.unref(); +w.on('exit', common.mustNotCall()); diff --git a/test/parallel/test-worker-ref.js b/test/parallel/test-worker-ref.js new file mode 100644 index 00000000000000..645fc0fbad8e37 --- /dev/null +++ b/test/parallel/test-worker-ref.js @@ -0,0 +1,29 @@ +'use strict'; +const common = require('../common'); +const { Worker } = require('worker_threads'); + +// Test that calling worker.unref() leads to 'beforeExit' being emitted, and +// that we can resurrect the worker using worker.ref() from there. + +const w = new Worker(` +const { parentPort } = require('worker_threads'); +parentPort.once('message', (msg) => { + parentPort.postMessage(msg); +}); +`, { eval: true }); + +process.once('beforeExit', common.mustCall(() => { + console.log('beforeExit'); + w.ref(); + w.postMessage({ hello: 'world' }); +})); + +w.once('message', common.mustCall((msg) => { + console.log('message', msg); +})); + +w.on('exit', common.mustCall(() => { + console.log('exit'); +})); + +w.unref();