工作线程支持


【Worker support】

为了能够从多个 Node.js 环境中加载,例如主线程和 Worker 线程,一个插件需要做到以下之一:

【In order to be loaded from multiple Node.js environments, such as a main thread and a Worker thread, an add-on needs to either:】

  • 成为一个 Node-API 插件,或者
  • 如上所述,使用 NODE_MODULE_INIT() 声明为上下文感知

为了支持 Worker 线程,插件在此类线程退出时需要清理它们可能分配的任何资源。这可以通过使用 AddEnvironmentCleanupHook() 函数来实现:

【In order to support Worker threads, addons need to clean up any resources they may have allocated when such a thread exits. This can be achieved through the usage of the AddEnvironmentCleanupHook() function:】

void AddEnvironmentCleanupHook(v8::Isolate* isolate,
                               void (*fun)(void* arg),
                               void* arg); 

此函数会添加一个钩子,在给定的 Node.js 实例关闭之前运行。如果有必要,可以在执行之前使用 RemoveEnvironmentCleanupHook() 移除这些钩子,该函数具有相同的签名。回调函数按先进后出顺序运行。

【This function adds a hook that will run before a given Node.js instance shuts down. If necessary, such hooks can be removed before they are run using RemoveEnvironmentCleanupHook(), which has the same signature. Callbacks are run in last-in first-out order.】

如果有必要,还可以使用一对额外的 AddEnvironmentCleanupHook()RemoveEnvironmentCleanupHook() 重载,其中清理钩子接受一个回调函数。它可用于关闭异步资源,例如由插件注册的任何 libuv 句柄。

【If necessary, there is an additional pair of AddEnvironmentCleanupHook() and RemoveEnvironmentCleanupHook() overloads, where the cleanup hook takes a callback function. This can be used for shutting down asynchronous resources, such as any libuv handles registered by the addon.】

下面的 addon.cc 使用了 AddEnvironmentCleanupHook

【The following addon.cc uses AddEnvironmentCleanupHook:】

// addon.cc
#include <node.h>
#include <assert.h>
#include <stdlib.h>

using node::AddEnvironmentCleanupHook;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;

// Note: In a real-world application, do not rely on static/global data.
static char cookie[] = "yum yum";
static int cleanup_cb1_called = 0;
static int cleanup_cb2_called = 0;

static void cleanup_cb1(void* arg) {
  Isolate* isolate = static_cast<Isolate*>(arg);
  HandleScope scope(isolate);
  Local<Object> obj = Object::New(isolate);
  assert(!obj.IsEmpty());  // assert VM is still alive
  assert(obj->IsObject());
  cleanup_cb1_called++;
}

static void cleanup_cb2(void* arg) {
  assert(arg == static_cast<void*>(cookie));
  cleanup_cb2_called++;
}

static void sanity_check(void*) {
  assert(cleanup_cb1_called == 1);
  assert(cleanup_cb2_called == 1);
}

// Initialize this addon to be context-aware.
NODE_MODULE_INIT(/* exports, module, context */) {
  Isolate* isolate = Isolate::GetCurrent();

  AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);
  AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);
  AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);
} 

通过运行在 JavaScript 中进行测试:

【Test in JavaScript by running:】

// test.js
require('./build/Release/addon');