Skip to content

Commit 2053dd0

Browse files
addaleaxtargos
authored andcommitted
worker: only unref port for stdin if we ref’ed it before
We set the `kStartedReading` flag from `_read()` for Worker stdio, and then `ref()` the port. However, the `.on('end')` handler is also attached when `._read()` is not called, e.g. when `process.stdin` inside a Worker is prematurely ended because stdin was not enabled by the parent thread. In that case, we should not call `.unref()` for stdin if we did not also call `.ref()` for it before. Fixes: #28144 PR-URL: #28153 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Rich Trott <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]>
1 parent c14e4d5 commit 2053dd0

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

lib/internal/worker/io.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,10 @@ class ReadableWorkerStdio extends Readable {
169169
this[kIncrementsPortRef] = true;
170170
this[kStartedReading] = false;
171171
this.on('end', () => {
172-
if (this[kIncrementsPortRef] && --this[kPort][kWaitingStreams] === 0)
173-
this[kPort].unref();
172+
if (this[kStartedReading] && this[kIncrementsPortRef]) {
173+
if (--this[kPort][kWaitingStreams] === 0)
174+
this[kPort].unref();
175+
}
174176
});
175177
}
176178

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const { Worker, isMainThread } = require('worker_threads');
5+
6+
// Regression test for https://github.com/nodejs/node/issues/28144.
7+
8+
if (isMainThread) {
9+
const w = new Worker(__filename);
10+
w.on('exit', common.mustCall((status) => {
11+
assert.strictEqual(status, 0);
12+
}));
13+
w.stdout.on('data', common.mustCall(10));
14+
} else {
15+
process.stdin.on('data', () => {});
16+
17+
for (let i = 0; i < 10; ++i) {
18+
process.stdout.write(`processing(${i})\n`, common.mustCall());
19+
}
20+
}

0 commit comments

Comments
 (0)