worker: fix crash when .unref() is called during exit

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: https://github.com/nodejs/node/pull/33394
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Anna Henningsen authored and Michaël Zasso committed 2020-05-16 11:13:30 +02:00
1 parent fda13d5dcf
commit 48b159562d
2 files changed
+18 -2

No files matched your search

+2 -2
View File
@@ -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);
}
@@ -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);
}
@@ -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);