Skip to content

Commit

Permalink
use AtomicBool
Browse files Browse the repository at this point in the history
  • Loading branch information
indutny authored and indutny-signal committed May 20, 2021
1 parent 8ea8d3d commit 34eb4d2
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions crates/neon-runtime/src/napi/tsfn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
use std::ffi::c_void;
use std::mem::MaybeUninit;
use std::sync::{Arc, Mutex};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::napi::bindings as napi;
use crate::raw::{Env, Local};
Expand Down Expand Up @@ -35,7 +36,7 @@ unsafe impl Sync for Tsfn {}
/// function for scheduling tasks to execute on a JavaScript thread.
pub struct ThreadsafeFunction<T> {
tsfn: Tsfn,
is_finalized: Arc<Mutex<bool>>,
is_finalized: Arc<AtomicBool>,
callback: fn(Option<Env>, T),
}

Expand Down Expand Up @@ -78,7 +79,7 @@ impl<T: Send + 'static> ThreadsafeFunction<T> {
callback: fn(Option<Env>, T),
) -> Self {
let mut result = MaybeUninit::uninit();
let is_finalized = Arc::new(Mutex::new(false));
let is_finalized = Arc::new(AtomicBool::new(false));

assert_eq!(
napi::create_threadsafe_function(
Expand Down Expand Up @@ -156,9 +157,9 @@ impl<T: Send + 'static> ThreadsafeFunction<T> {
// Provides a C ABI wrapper for a napi callback notifying us about tsfn
// being finalized.
unsafe extern "C" fn finalize(_env: Env, data: *mut c_void, _hint: *mut c_void) {
let is_finalized = Arc::from_raw(data as *mut Mutex<bool>);
let is_finalized = Arc::from_raw(data as *mut AtomicBool);

*is_finalized.lock().unwrap() = true;
is_finalized.store(true, Ordering::Relaxed);
}

// Provides a C ABI wrapper for invoking the user supplied function pointer
Expand All @@ -181,7 +182,7 @@ impl<T> Drop for ThreadsafeFunction<T> {
fn drop(&mut self) {
// tsfn was already finalized by `Environment::CleanupHandles()` in
// Node.js
if *self.is_finalized.lock().unwrap() {
if self.is_finalized.load(Ordering::Relaxed) {
return;
}

Expand Down

0 comments on commit 34eb4d2

Please sign in to comment.