

using custom logic with other thread-safe APIs to ensure that all threads call Release() in order to decrease the active thread count to 0.calling Abort() and have each thread either call BlockingCall() or Release().Initiating cleanup/destruction, for example by ….The new thread can now use BlockingCall(). Calling Acquire() and creating a new native thread.Creating a thread-safe function via New() with initial thread count of 1.One way to handle this scenario is to expose several native JavaScript functions that interact with the thread-safe function APIs by: Creating ThreadsĪnother common use-case is to dynamically create and destroy threads based on various logic at run-time. Once all threads have made a call to Release(), the thread-safe function is destroyed. Each thread will have its own access to the thread-safe function until it calls Release(). If the amount of threads is known at thread-safe function creation, set the initial_thread_count parameter to this number in the call to New().

Here are two general approaches to using thread-safe functions within applications: Known Number of Threads Once the number of active threads reaches zero, the thread-safe function is destroyed, running the finalizer callback on the main thread if provided.

This number starts at the initial thread count parameter in New(), increased via Acquire(), and decreased via Released(). The thread-safe function manages its lifecycle through counting the number of threads actively utilizing it. Multiple threads can utilize the thread-safe function simultaneously. This will add an entry to the underlying thread-safe function’s queue, to be handled asynchronously on the main thread during its processing of the event loop. Threads may call into JavaScript via BlockingCall. Finalizer data: Optional data ( data parameter) to provide to the finalizer callback.

Finalizer: Optional callback ( finalizeCallback parameter) to run at destruction of the thread-safe function, when all threads have finished using it.Context: Optional, arbitrary data ( context parameter) to associate with the thread-safe function.This function is either (a) automatically ran with no arguments when called via the no-argument BlockingCall() overloads, or (b) passed as an argument to the callback function provided in the BlockingCall(DataType* data, Callback callback) overloads. JavaScript function: Callback to run ( callback parameter).The amount of entries allowed in the queue before returning a “queue full” error on NonBlockingCall() is controlled via the maxQueueSize parameter (specify 0 for unlimited queue) Message queue: Requests to run the JavaScript function are placed in a queue, processed asynchronously by the main thread.New (napi_env env, const Function & callback, const Object & resource ,
