Skip to content

Commit c51735f

Browse files
addaleaxdanbev
authored andcommitted
worker: release native Worker object earlier
Destroy the `Worker` class earlier, because we don’t need access to it once the thread has stopped and all resources have been cleaned up. PR-URL: nodejs#26542 Fixes: nodejs#26535 Reviewed-By: Gireesh Punathil <[email protected]> Reviewed-By: Joyee Cheung <[email protected]> Reviewed-By: Gus Caplan <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Colin Ihrig <[email protected]>
1 parent 3753f9c commit c51735f

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/node_worker.cc

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,9 @@ Worker::Worker(Environment* env,
136136
env->inspector_agent()->GetParentHandle(thread_id_, url);
137137
#endif
138138

139+
// Mark this Worker object as weak until we actually start the thread.
140+
MakeWeak();
141+
139142
Debug(this, "Preparation for worker %llu finished", thread_id_);
140143
}
141144

@@ -412,14 +415,10 @@ void Worker::OnThreadStopped() {
412415

413416
Worker::~Worker() {
414417
Mutex::ScopedLock lock(mutex_);
415-
JoinThread();
416418

417419
CHECK(thread_stopper_.IsStopped());
418420
CHECK(thread_joined_);
419421

420-
// This has most likely already happened within the worker thread -- this
421-
// is just in case Worker creation failed early.
422-
423422
Debug(this, "Worker %llu destroyed", thread_id_);
424423
}
425424

@@ -509,6 +508,10 @@ void Worker::StartThread(const FunctionCallbackInfo<Value>& args) {
509508
ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
510509
Mutex::ScopedLock lock(w->mutex_);
511510

511+
// The object now owns the created thread and should not be garbage collected
512+
// until that finishes.
513+
w->ClearWeak();
514+
512515
w->env()->add_sub_worker_context(w);
513516
w->thread_joined_ = false;
514517
w->thread_stopper_.SetStopped(false);
@@ -518,6 +521,7 @@ void Worker::StartThread(const FunctionCallbackInfo<Value>& args) {
518521
CHECK(w_->thread_stopper_.IsStopped());
519522
w_->parent_port_ = nullptr;
520523
w_->JoinThread();
524+
delete w_;
521525
});
522526

523527
uv_thread_options_t thread_options;
@@ -545,6 +549,7 @@ void Worker::StopThread(const FunctionCallbackInfo<Value>& args) {
545549
Debug(w, "Worker %llu is getting stopped by parent", w->thread_id_);
546550
w->Exit(1);
547551
w->JoinThread();
552+
delete w;
548553
}
549554

550555
void Worker::Ref(const FunctionCallbackInfo<Value>& args) {

0 commit comments

Comments
 (0)