Skip to content

Commit fab5d00

Browse files
committed
fixup! worker: prevent event loop starvation through MessagePorts
1 parent 56d0e4a commit fab5d00

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

src/node_messaging.cc

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -604,21 +604,26 @@ void MessagePort::OnMessage() {
604604
HandleScope handle_scope(env()->isolate());
605605
Local<Context> context = object(env()->isolate())->CreationContext();
606606

607-
ssize_t processing_limit;
607+
size_t processing_limit;
608608
{
609609
Mutex::ScopedLock(data_->mutex_);
610-
processing_limit = data_->incoming_messages_.size();
610+
processing_limit = std::max(data_->incoming_messages_.size(),
611+
static_cast<size_t>(1000));
611612
}
612613

613614
// data_ can only ever be modified by the owner thread, so no need to lock.
614615
// However, the message port may be transferred while it is processing
615616
// messages, so we need to check that this handle still owns its `data_` field
616617
// on every iteration.
617618
while (data_) {
618-
if (--processing_limit < 0) {
619+
if (processing_limit-- == 0) {
619620
// Prevent event loop starvation by only processing those messages without
620621
// interruption that were already present when the OnMessage() call was
621-
// first triggered.
622+
// first triggered, but at least 1000 messages because otherwise the
623+
// overhead of repeatedly triggering the uv_async_t instance becomes
624+
// noticable, at least on Windows.
625+
// (That might require more investigation by somebody more familiar with
626+
// Windows.)
622627
TriggerAsync();
623628
return;
624629
}

test/parallel/test-worker-message-port-infinite-message-loop.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,6 @@ port1.on('message', () => {
2424

2525
port2.postMessage(0);
2626

27+
// This is part of the test -- the event loop should be available and not stall
28+
// out due to the recursive .postMessage() calls.
2729
setTimeout(common.mustCall(), 0);

0 commit comments

Comments
 (0)