调用线程安全的函数


¥Calling a thread-safe function

napi_call_threadsafe_function() 可用于启动对 JavaScript 的调用。napi_call_threadsafe_function() 接受一个参数,该参数控制 API 是否以阻塞方式运行。如果设置为 napi_tsfn_nonblocking,API 将以非阻塞方式运行,如果队列已满则返回 napi_queue_full,从而阻止数据成功添加到队列中。如果设置为 napi_tsfn_blocking,API 将阻塞,直到队列中有可用空间。如果创建的线程安全函数的最大队列大小为 0,则 napi_call_threadsafe_function() 永远不会阻塞。

¥napi_call_threadsafe_function() can be used for initiating a call into JavaScript. napi_call_threadsafe_function() accepts a parameter which controls whether the API behaves blockingly. If set to napi_tsfn_nonblocking, the API behaves non-blockingly, returning napi_queue_full if the queue was full, preventing data from being successfully added to the queue. If set to napi_tsfn_blocking, the API blocks until space becomes available in the queue. napi_call_threadsafe_function() never blocks if the thread-safe function was created with a maximum queue size of 0.

不应从 JavaScript 线程使用 napi_tsfn_blocking 调用 napi_call_threadsafe_function(),因为如果队列已满,可能会导致 JavaScript 线程死锁。

¥napi_call_threadsafe_function() should not be called with napi_tsfn_blocking from a JavaScript thread, because, if the queue is full, it may cause the JavaScript thread to deadlock.

对 JavaScript 的实际调用由通过 call_js_cb 参数给出的回调控制。对于通过成功调用 napi_call_threadsafe_function() 放入队列中的每个值,在主线程上调用 call_js_cb 一次。如果没有给出这样的回调,将使用默认回调,并且生成的 JavaScript 调用将没有参数。call_js_cb 回调在其参数中接收要作为 napi_value 调用的 JavaScript 函数,以及创建 napi_threadsafe_function 时使用的 void* 上下文指针,以及由其中一个辅助线程创建的下一个数据指针。然后,回调可以使用诸如 napi_call_function() 之类的 API 来调用 JavaScript。

¥The actual call into JavaScript is controlled by the callback given via the call_js_cb parameter. call_js_cb is invoked on the main thread once for each value that was placed into the queue by a successful call to napi_call_threadsafe_function(). If such a callback is not given, a default callback will be used, and the resulting JavaScript call will have no arguments. The call_js_cb callback receives the JavaScript function to call as a napi_value in its parameters, as well as the void* context pointer used when creating the napi_threadsafe_function, and the next data pointer that was created by one of the secondary threads. The callback can then use an API such as napi_call_function() to call into JavaScript.

回调也可以在 envcall_js_cb 都设置为 NULL 的情况下调用,以指示不再可能调用 JavaScript,而项目仍保留在可能需要释放的队列中。这通常发生在 Node.js 进程退出而线程安全功能仍处于活动状态时。

¥The callback may also be invoked with env and call_js_cb both set to NULL to indicate that calls into JavaScript are no longer possible, while items remain in the queue that may need to be freed. This normally occurs when the Node.js process exits while there is a thread-safe function still active.

没有必要通过 napi_make_callback() 调用 JavaScript,因为 Node-API 在适合回调的上下文中运行 call_js_cb

¥It is not necessary to call into JavaScript via napi_make_callback() because Node-API runs call_js_cb in a context appropriate for callbacks.