线程安全函数的引用计数


【Reference counting of thread-safe functions】

napi_threadsafe_function 对象存在期间,可以向其中添加和移除线程。因此,除了在创建时指定初始线程数之外,还可以调用 napi_acquire_threadsafe_function 来表示一个新线程将开始使用线程安全函数。同样,可以调用 napi_release_threadsafe_function 来表示一个现有线程将停止使用该线程安全函数。

【Threads can be added to and removed from a napi_threadsafe_function object during its existence. Thus, in addition to specifying an initial number of threads upon creation, napi_acquire_threadsafe_function can be called to indicate that a new thread will start making use of the thread-safe function. Similarly, napi_release_threadsafe_function can be called to indicate that an existing thread will stop making use of the thread-safe function.】

napi_threadsafe_function 对象在每个使用该对象的线程都调用了 napi_release_threadsafe_function() 或在调用 napi_call_threadsafe_function 后收到 napi_closing 返回状态时会被销毁。在 napi_threadsafe_function 被销毁之前,队列会被清空。napi_release_threadsafe_function() 应该是与给定 napi_threadsafe_function 一起调用的最后一个 API,因为调用完成后,无法保证 napi_threadsafe_function 仍然被分配。出于同样的原因,在调用 napi_call_threadsafe_function 并收到 napi_closing 返回值后,不要使用线程安全函数。与 napi_threadsafe_function 相关的数据可以在传递给 napi_create_threadsafe_function()napi_finalize 回调中释放。napi_create_threadsafe_function 的参数 initial_thread_count 标记了线程安全函数的初始获取次数,而不是在创建时多次调用 napi_acquire_threadsafe_function

一旦使用 napi_threadsafe_function 的线程数变为零,就没有其他线程可以通过调用 napi_acquire_threadsafe_function() 来开始使用它。实际上,所有与之相关的后续 API 调用(除了 napi_release_threadsafe_function())都会返回 napi_closing 错误值。

【Once the number of threads making use of a napi_threadsafe_function reaches zero, no further threads can start making use of it by calling napi_acquire_threadsafe_function(). In fact, all subsequent API calls associated with it, except napi_release_threadsafe_function(), will return an error value of napi_closing.】

可以通过向 napi_release_threadsafe_function() 提供 napi_tsfn_abort 值来“中止”线程安全函数。这将导致与线程安全函数相关的所有后续 API(除了 napi_release_threadsafe_function())在其引用计数达到零之前就返回 napi_closing。特别是,napi_call_threadsafe_function() 将返回 napi_closing,从而通知线程不再可能对线程安全函数进行异步调用。这可以用作终止线程的标准。当从 napi_call_threadsafe_function() 接收到 napi_closing 返回值时,线程不得再使用该线程安全函数,因为它不再保证被分配。

【The thread-safe function can be "aborted" by giving a value of napi_tsfn_abort to napi_release_threadsafe_function(). This will cause all subsequent APIs associated with the thread-safe function except napi_release_threadsafe_function() to return napi_closing even before its reference count reaches zero. In particular, napi_call_threadsafe_function() will return napi_closing, thus informing the threads that it is no longer possible to make asynchronous calls to the thread-safe function. This can be used as a criterion for terminating the thread. Upon receiving a return value of napi_closing from napi_call_threadsafe_function() a thread must not use the thread-safe function anymore because it is no longer guaranteed to be allocated.