我正在尝试实现与node.js集成的C ++扩展。此扩展将在内部调用一些阻塞调用,因此它需要为node.js世界提供一个非阻塞接口。
如https://nodejs.org/api/addons.html中所指定,有两种方法来实现非阻塞回调:
通过使用对JavaScript函数的简单回调。因此,我的扩展程序必须生成一个线程并立即返回,然后让该线程调用阻塞代码,然后在返回时调用JavaScript回调。这似乎相对容易实现。
b)如果我理解正确,请使用libuv库将事件发布到node.js事件循环。我没有详细阅读libuv文档,但这实现起来似乎很复杂。
我的偏好当然是a),但是我不知道其中的含义。如果从其他线程调用回调,从而将node.js标准方法塞入非阻塞IO,会出现任何问题吗?还是需要使用libuv来正确处理我的代码及其阻塞调用的线程?
非常感谢您的帮助。
从其他线程调用回调不是一种选择,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();
}
在后台,它将使用libuv线程池处理代码并在主线程上调用回调。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句