Skip to content

Commit 331f604

Browse files
yaelheBethGriggs
authored andcommitted
worker: drain messages from internal message port
When the worker thread exits, drain the messages also from the internal message port so that the call to 'kDispose' will occur only after all the messages from the worker were processed in the parent, so stdio messages from the worker will be successfully pushed to their target streams in the parent. PR-URL: #24932 Fixes: #24636 Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: Anna Henningsen <anna@addaleax.net>
1 parent f854701 commit 331f604

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

lib/internal/worker.js

+1
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,7 @@ class Worker extends EventEmitter {
317317
[kOnExit](code) {
318318
debug(`[${threadId}] hears end event for Worker ${this.threadId}`);
319319
MessagePortPrototype.drain.call(this[kPublicPort]);
320+
MessagePortPrototype.drain.call(this[kPort]);
320321
this[kDispose]();
321322
this.emit('exit', code);
322323
this.removeAllListeners();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Flags: --experimental-worker
2+
'use strict';
3+
require('../common');
4+
5+
// This test ensures that the messages from the internal
6+
// message port are drained before the call to 'kDispose',
7+
// and so all the stdio messages from the worker are processed
8+
// in the parent and are pushed to their target streams.
9+
10+
const assert = require('assert');
11+
const {
12+
Worker,
13+
isMainThread,
14+
parentPort,
15+
threadId,
16+
} = require('worker_threads');
17+
18+
if (isMainThread) {
19+
const workerIdsToOutput = new Map();
20+
21+
for (let i = 0; i < 2; i++) {
22+
const worker = new Worker(__filename, { stdout: true });
23+
const workerOutput = [];
24+
workerIdsToOutput.set(worker.threadId, workerOutput);
25+
worker.on('message', console.log);
26+
worker.stdout.on('data', (chunk) => {
27+
workerOutput.push(chunk.toString().trim());
28+
});
29+
}
30+
31+
process.on('exit', () => {
32+
for (const [threadId, workerOutput] of workerIdsToOutput) {
33+
assert.ok(workerOutput.includes(`1 threadId: ${threadId}`));
34+
assert.ok(workerOutput.includes(`2 threadId: ${threadId}`));
35+
}
36+
});
37+
} else {
38+
console.log(`1 threadId: ${threadId}`);
39+
console.log(`2 threadId: ${threadId}`);
40+
parentPort.postMessage(Array(100).fill(1));
41+
}

0 commit comments

Comments
 (0)