diff --git a/src/bun.js/web_worker.zig b/src/bun.js/web_worker.zig index 87982931a9..950f93d71b 100644 --- a/src/bun.js/web_worker.zig +++ b/src/bun.js/web_worker.zig @@ -690,9 +690,18 @@ const WebWorkerLifecycleHandle = struct { } pub fn requestTermination(self: *WebWorkerLifecycleHandle) void { + if (self.requested_terminate.load(.acquire)) { + return; + } + self.ref(); self.mutex.lock(); - self.requested_terminate.store(true, .monotonic); + + if (self.requested_terminate.swap(true, .monotonic)) { + self.mutex.unlock(); + self.deref(); + return; + } if (self.worker) |worker| { self.worker = null; @@ -701,6 +710,7 @@ const WebWorkerLifecycleHandle = struct { worker.deref(); } else { self.mutex.unlock(); + // Let the reference counting system handle deinitialization self.deref(); } @@ -713,7 +723,7 @@ const WebWorkerLifecycleHandle = struct { if (self.requested_terminate.swap(false, .acquire)) { // we already requested to terminate, therefore this handle has // already been consumed on the other thread and we are able to free - // it. + // it. Let the reference counting system handle deinitialization. self.mutex.unlock(); self.deref(); return;