异步线程安全函数调用


【Asynchronous thread-safe function calls】

JavaScript 函数通常只能从本地插件的主线程调用。如果插件创建了额外的线程,那么那些需要 napi_envnapi_valuenapi_ref 的 Node-API 函数不能从这些线程中调用。

【JavaScript functions can normally only be called from a native addon's main thread. If an addon creates additional threads, then Node-API functions that require a napi_env, napi_value, or napi_ref must not be called from those threads.】

当一个插件有额外的线程,并且需要根据这些线程完成的处理来调用 JavaScript 函数时,这些线程必须与插件的主线程进行通信,以便主线程可以代表它们调用 JavaScript 函数。线程安全的函数 API 提供了一种简便的方法来实现这一点。

【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.】

这些 API 提供了 napi_threadsafe_function 类型,以及用于创建、销毁和调用此类型对象的 API。 napi_create_threadsafe_function() 会为一个 napi_value 创建一个持久引用,该 napi_value 保存一个可以从多个线程调用的 JavaScript 函数。调用是异步发生的。这意味着将用于调用 JavaScript 回调的值会被放入队列中,并且队列中的每个值最终都会调用该 JavaScript 函数。

【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.】

在创建 napi_threadsafe_function 时,可以提供一个 napi_finalize 回调。当线程安全函数即将被销毁时,该回调将在主线程上被调用。它会接收在构造期间提供的上下文和终结数据,并提供一个机会用于清理线程,例如通过调用 uv_thread_join()除了主循环线程,终结回调完成后,不应有其他线程使用该线程安全函数。

【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.

在调用 napi_create_threadsafe_function() 时提供的 context 可以通过在任意线程调用 napi_get_threadsafe_function_context() 来获取。

【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().】