Skip to content

Commit 62801b9

Browse files
addaleaxBridgeAR
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: #26542 Fixes: #26535 Reviewed-By: Gireesh Punathil <gpunathi@in.ibm.com> Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com> Reviewed-By: Gus Caplan <me@gus.host> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
1 parent 9768ec4 commit 62801b9

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/node_worker.cc

+9-4
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

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

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

522526
uv_thread_options_t thread_options;
@@ -544,6 +548,7 @@ void Worker::StopThread(const FunctionCallbackInfo<Value>& args) {
544548
Debug(w, "Worker %llu is getting stopped by parent", w->thread_id_);
545549
w->Exit(1);
546550
w->JoinThread();
551+
delete w;
547552
}
548553

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

0 commit comments

Comments
 (0)