Skip to content

Commit

Permalink
worker: fix crash when .unref() is called during exit
Browse files Browse the repository at this point in the history
To be more precise, fix a crash when `worker.unref()` is called
from a message on the Worker that is not emitted before the Worker
thread has stopped.

PR-URL: #33394
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
addaleax authored and targos committed May 16, 2020
1 parent fda13d5 commit 48b1595
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/node_worker.cc
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,7 @@ void Worker::StopThread(const FunctionCallbackInfo<Value>& args) {
void Worker::Ref(const FunctionCallbackInfo<Value>& args) {
Worker* w;
ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
if (!w->has_ref_) {
if (!w->has_ref_ && !w->thread_joined_) {
w->has_ref_ = true;
w->env()->add_refs(1);
}
Expand All @@ -674,7 +674,7 @@ void Worker::Ref(const FunctionCallbackInfo<Value>& args) {
void Worker::Unref(const FunctionCallbackInfo<Value>& args) {
Worker* w;
ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
if (w->has_ref_) {
if (w->has_ref_ && !w->thread_joined_) {
w->has_ref_ = false;
w->env()->add_refs(-1);
}
Expand Down
16 changes: 16 additions & 0 deletions test/parallel/test-worker-unref-from-message-during-exit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use strict';
const common = require('../common');
const { Worker } = require('worker_threads');

// This used to crash because the `.unref()` was unexpected while the Worker
// was exiting.

const w = new Worker(`
require('worker_threads').parentPort.postMessage({});
`, { eval: true });
w.on('message', common.mustCall(() => {
w.unref();
}));

// Wait a bit so that the 'message' event is emitted while the Worker exits.
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);

0 comments on commit 48b1595

Please sign in to comment.