Node.js和C/C++集成:如何正确实现回调?

Lui*_*spo 3 c++ multithreading node.js node.js-addon

我正在尝试实现与node.js集成的C++扩展.此扩展将在内部调用一些阻塞调用,因此它需要为node.js世界提供非阻塞接口.

https://nodejs.org/api/addons.html中所述,有两种方法可以实现非阻塞回调:

a)通过使用JavaScript函数的简单回调.所以我的扩展必须生成一个线程并立即返回,让该线程调用阻塞代码,然后在返回时调用JavaScript回调.这似乎相对简单.

b)通过使用libuv库,如果我理解正确,将事件发布到node.js事件循环.我没有详细阅读过libuv文档,但实现起来似乎相当复杂.

我的偏好当然是a),但我不知道其含义是什么.如果从不同的线程调用回调是否有任何问题,从而将node.js标准方法限制为非阻塞IO?或者是否需要使用libuv来正确处理我的代码及其阻塞调用的线程?

非常感谢您的帮助.

vku*_*kin 5

从另一个线程调用回调不是一个选项,v8不允许这样做.所以你必须和b一起去.实际上并没有那么难.我建议使用nan来完成这项任务.以下是docs的示例:

class PiWorker : public NanAsyncWorker {
 public:
  PiWorker(NanCallback *callback, int points)
    : NanAsyncWorker(callback), points(points) {}
  ~PiWorker() {}

  // Executed inside the worker-thread.
  // It is not safe to access V8, or V8 data structures
  // here, so everything we need for input and output
  // should go on `this`.
  void Execute () {
    estimate = Estimate(points);
  }

  // Executed when the async work is complete
  // this function will be run inside the main event loop
  // so it is safe to use V8 again
  void HandleOKCallback () {
    NanScope();

    Local<Value> argv[] = {
        NanNull()
      , NanNew<Number>(estimate)
    };

    callback->Call(2, argv);
  };

 private:
  int points;
  double estimate;
};

// Asynchronous access to the `Estimate()` function
NAN_METHOD(CalculateAsync) {
  NanScope();

  int points = args[0]->Uint32Value();
  NanCallback *callback = new NanCallback(args[1].As<Function>());

  NanAsyncQueueWorker(new PiWorker(callback, points));
  NanReturnUndefined();
}
Run Code Online (Sandbox Code Playgroud)

它将处理使用libuv线程池调用代码并在主线程上调用回调.