From e97bbd085572b4b43e23914123e8e10b0991c212 Mon Sep 17 00:00:00 2001 From: Fedor Indutny Date: Sat, 22 May 2021 12:35:24 -0700 Subject: [PATCH] more locks --- crates/neon-runtime/src/napi/tsfn.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/neon-runtime/src/napi/tsfn.rs b/crates/neon-runtime/src/napi/tsfn.rs index bdb118fd9..f76f5136c 100644 --- a/crates/neon-runtime/src/napi/tsfn.rs +++ b/crates/neon-runtime/src/napi/tsfn.rs @@ -119,12 +119,28 @@ impl ThreadsafeFunction { data, })); - let status = - unsafe { napi::call_threadsafe_function(self.tsfn.0, callback as *mut _, is_blocking) }; + let status = { + // Hold the lock before entering `call_threadsafe_function` so that + // `finalize_cb` would never complete. + let is_finalized = self.is_finalized.lock().unwrap(); + + if *is_finalized { + napi::Status::Closing + } else { + unsafe { + napi::call_threadsafe_function(self.tsfn.0, callback as *mut _, is_blocking) + } + } + }; if status == napi::Status::Ok { Ok(()) } else { + // Prevent further calls to `call_threadsafe_function` + if status == napi::Status::Closing { + *self.is_finalized.lock().unwrap() = true; + } + // If the call failed, the callback won't execute let callback = unsafe { Box::from_raw(callback) };