pub struct ThreadsafeFunction<T: 'static, ES: T = CalleeHandled> { /* private fields */ }
Expand description

Communicate with the addon’s main thread by invoking a JavaScript function from other threads.

Example

An example of using ThreadsafeFunction:

#[macro_use]
extern crate napi_derive;

use std::thread;

use napi::{
    threadsafe_function::{
        ThreadSafeCallContext, ThreadsafeFunctionCallMode, ThreadsafeFunctionReleaseMode,
    },
    CallContext, Error, JsFunction, JsNumber, JsUndefined, Result, Status,
};

#[js_function(1)]
pub fn test_threadsafe_function(ctx: CallContext) -> Result<JsUndefined> {
  let func = ctx.get::<JsFunction>(0)?;

  let tsfn =
      ctx
          .env
          .create_threadsafe_function(&func, 0, |ctx: ThreadSafeCallContext<Vec<u32>>| {
            ctx.value
                .iter()
                .map(|v| ctx.env.create_uint32(*v))
                .collect::<Result<Vec<JsNumber>>>()
          })?;

  let tsfn_cloned = tsfn.clone();

  thread::spawn(move || {
      let output: Vec<u32> = vec![0, 1, 2, 3];
      // It's okay to call a threadsafe function multiple times.
      tsfn.call(Ok(output.clone()), ThreadsafeFunctionCallMode::Blocking);
  });

  thread::spawn(move || {
      let output: Vec<u32> = vec![3, 2, 1, 0];
      // It's okay to call a threadsafe function multiple times.
      tsfn_cloned.call(Ok(output.clone()), ThreadsafeFunctionCallMode::NonBlocking);
  });

  ctx.env.get_undefined()
}

Implementations

See napi_ref_threadsafe_function for more information.

“ref” is a keyword so that we use “refer” here.

See napi_unref_threadsafe_function for more information.

Get the raw ThreadSafeFunction pointer

See napi_call_threadsafe_function for more information.

See napi_call_threadsafe_function for more information.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Executes the destructor for this type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.