From 071dcff9ebe0e631e60d1915a93ea9fd2583348e Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 26 Feb 2021 18:36:51 +0800 Subject: [PATCH] feat(napi): add back clone trait to ThreadsafeFunction --- napi/src/threadsafe_function.rs | 35 ++++++++++++++++++--------------- test_module/src/napi4/tsfn.rs | 6 +++--- 2 files changed, 22 insertions(+), 19 deletions(-) diff --git a/napi/src/threadsafe_function.rs b/napi/src/threadsafe_function.rs index f60dd8f4..61ce0c2e 100644 --- a/napi/src/threadsafe_function.rs +++ b/napi/src/threadsafe_function.rs @@ -68,7 +68,7 @@ impl Into for ThreadsafeFunctionCallMode { /// .collect::>>() /// })?; /// -/// let tsfn_cloned = tsfn.try_clone()?; +/// let tsfn_cloned = tsfn.clone(); /// /// thread::spawn(move || { /// let output: Vec = vec![0, 1, 2, 3]; @@ -91,6 +91,24 @@ pub struct ThreadsafeFunction { _phantom: PhantomData, } +impl Clone for ThreadsafeFunction { + fn clone(&self) -> Self { + if !self.aborted.load(Ordering::Acquire) { + let acquire_status = unsafe { sys::napi_acquire_threadsafe_function(self.raw_tsfn) }; + debug_assert!( + acquire_status == sys::Status::napi_ok, + "Acquire threadsafe function failed in clone" + ); + } + + Self { + raw_tsfn: self.raw_tsfn, + aborted: Arc::clone(&self.aborted), + _phantom: PhantomData, + } + } +} + unsafe impl Send for ThreadsafeFunction {} unsafe impl Sync for ThreadsafeFunction {} @@ -203,21 +221,6 @@ impl ThreadsafeFunction { Ok(()) } - pub fn try_clone(&self) -> Result { - if self.aborted.load(Ordering::Acquire) { - return Err(Error::new( - Status::Closing, - format!("Can not clone, Thread safe function already aborted"), - )); - } - check_status!(unsafe { sys::napi_acquire_threadsafe_function(self.raw_tsfn) })?; - Ok(Self { - raw_tsfn: self.raw_tsfn, - aborted: Arc::clone(&self.aborted), - _phantom: PhantomData, - }) - } - /// Get the raw `ThreadSafeFunction` pointer pub fn raw(&self) -> sys::napi_threadsafe_function { self.raw_tsfn diff --git a/test_module/src/napi4/tsfn.rs b/test_module/src/napi4/tsfn.rs index 1f5cfd2b..9358fa89 100644 --- a/test_module/src/napi4/tsfn.rs +++ b/test_module/src/napi4/tsfn.rs @@ -23,7 +23,7 @@ pub fn test_threadsafe_function(ctx: CallContext) -> Result { .collect::>>() })?; - let tsfn_cloned = tsfn.try_clone()?; + let tsfn_cloned = tsfn.clone(); thread::spawn(move || { let output: Vec = vec![0, 1, 2, 3]; @@ -55,7 +55,7 @@ pub fn test_abort_threadsafe_function(ctx: CallContext) -> Result { .collect::>>() })?; - let tsfn_cloned = tsfn.try_clone()?; + let tsfn_cloned = tsfn.clone(); tsfn_cloned.abort()?; ctx.env.get_boolean(tsfn.aborted()) @@ -92,7 +92,7 @@ pub fn test_call_aborted_threadsafe_function(ctx: CallContext) -> Result