JavaScript functions can normally only be called from a native addon’s main
thread. If an addon creates additional threads, then N-API functions that
require a napi_env
, napi_value
, or napi_ref
must not be called from those
threads.
When an addon has additional threads and JavaScript functions need to be invoked based on the processing completed by those threads, those threads must communicate with the addon’s main thread so that the main thread can invoke the JavaScript function on their behalf. The thread-safe function APIs provide an easy way to do this.
These APIs provide the type napi_threadsafe_function
as well as APIs to
create, destroy, and call objects of this type.
napi_create_threadsafe_function()
creates a persistent reference to a
napi_value
that holds a JavaScript function which can be called from multiple
threads. The calls happen asynchronously. This means that values with which the
JavaScript callback is to be called will be placed in a queue, and, for each
value in the queue, a call will eventually be made to the JavaScript function.
Upon creation of a napi_threadsafe_function
a napi_finalize
callback can be
provided. This callback will be invoked on the main thread when the thread-safe
function is about to be destroyed. It receives the context and the finalize data
given during construction, and provides an opportunity for cleaning up after the
threads e.g. by calling uv_thread_join()
. Aside from the main loop thread,
no threads should be using the thread-safe function after the finalize callback
completes.
The context
given during the call to napi_create_threadsafe_function()
can
be retrieved from any thread with a call to
napi_get_threadsafe_function_context()
.