异步线程安全函数调用
¥Asynchronous thread-safe function calls
JavaScript 函数通常只能从原生插件的主线程调用。如果插件创建了额外的线程,则不得从这些线程调用需要 napi_env
、napi_value
或 napi_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
的持久引用,该引用包含可从多个线程调用的 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()
。除了主循环线程之外,在 finalize 回调完成后,没有线程应该使用线程安全函数。
¥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()
.