从不同的线程调用回调不是一个选项,v8 不允许这样做。所以你必须选择b。实际上实施起来并不难。我建议使用nan来完成这项任务。这是来自文档的示例:
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 线程池调用您的代码并在主线程上调用回调。