Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/node_messaging.cc
Original file line number Diff line number Diff line change
Expand Up @@ -609,11 +609,20 @@ void MessagePort::OnMessage() {
HandleScope handle_scope(env()->isolate());
Local<Context> context = object(env()->isolate())->CreationContext();

int count = 0;

// data_ can only ever be modified by the owner thread, so no need to lock.
// However, the message port may be transferred while it is processing
// messages, so we need to check that this handle still owns its `data_` field
// on every iteration.
while (data_) {
if (count++ == 100) {
// Prevent event loop starvation by allowing a maximum of 100 messages
// to be processed without interruption.
TriggerAsync();
return;
}

HandleScope handle_scope(env()->isolate());
Context::Scope context_scope(context);

Expand Down
27 changes: 27 additions & 0 deletions test/parallel/test-worker-message-port-infinite-message-loop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'use strict';
const common = require('../common');
const assert = require('assert');

const { MessageChannel } = require('worker_threads');

// Make sure that an infinite asynchronous .on('message')/postMessage loop
// does not lead to a stack overflow and does not starve the event loop.
// We schedule timeouts both from before the the .on('message') handler and
// inside of it, which both should run.

const { port1, port2 } = new MessageChannel();
let count = 0;
port1.on('message', () => {
if (count === 0) {
setTimeout(common.mustCall(() => {
port1.close();
}), 0);
}

port2.postMessage(0);
assert(count++ < 10000, `hit ${count} loop iterations`);
Copy link
Member

@joyeecheung joyeecheung Jun 3, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It may be useful to document that this depends on the constant in the source - in case someone wants to turn it down later. Or we could also export the constant and do some math here..

(Non-blocking BTW)

});

port2.postMessage(0);

setTimeout(common.mustCall(), 0);