Node.js and C / C ++ integration: how to properly implement callbacks?

I am trying to implement a C ++ extension to integrate with node.js. This extension will internally make some blocking calls, so it needs to provide a non-blocking interface to the node.js world.

As stated at https://nodejs.org/api/addons.html , there are two ways to implement non-blocking callbacks:

a) Using a simple JavaScript function callback. So my extension would have to spawn a thread and return immediately, and let that thread call the blocking code and then call the JavaScript callback on return. This seems to be relatively easy to implement.

b) Using the libuv library, so that if I understand correctly, send the event to the node.js event loop. I haven't read the libuv documentation in detail, but it seems quite complicated to implement.

My preference is of course a), but I have no idea what the implications are. Are there problems if the callback is called from a different thread, thus cimcurventing the standard node.js approach to non-blocking IO? Or does libuv need to be used to properly handle threads for my code and its blocking calls?

Many thanks for your help.

+3


source to share


1 answer


Calling a callback from another thread is not a parameter, v8 does not allow this. So you need to go with b. It's not really that hard to implement. I recommend using nan for this task. Here's an example from the 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();
}

      



Under the hood, calling your code using libuv's thread pool and calling a callback on the main thread will be handled.

+5


source







All Articles