从 Web 工作线程调用C++ v8 函数

calling C++ v8 function from a web worker thread

本文关键字:C++ v8 函数 调用 线程 Web 工作      更新时间:2023-10-16

我在我的javascript代码中创建了一个Web worker thread。我正在尝试使用 node-gyp 和 V8 从线程调用 C++ 函数。但我无法让它工作。

这是 hello.cc 的代码

#include <v8.h>
using namespace v8;
extern std::string myhello();
Handle<Value> Method(const Arguments& args) { 
  HandleScope scope;
  return scope.Close(String::New("hello"));
}
void init(Handle<Object> exports) {
  exports->Set(String::NewSymbol("hello"),
      FunctionTemplate::New(Method)->GetFunction()
    );
}
NODE_MODULE(hello, init)

这是myhello的代码.js

var addon = require('./build/Release/hello');
var thread = require('webworker-threads');
var t = thread.create();
console.log(t.eval("addon.hello()")); 

当我运行node myhello.js时,我得到以下输出

{ id: 0,
  eval: [Function: eval],
  load: [Function: load],
  emit: [Function: emit],
  emitSerialized: [Function: emitSerialized],
  destroy: [Function: destroy],
  on: [Function],
  once: [Function],
  removeAllListeners: [Function],
  dispatchEvents: [Function],
  _on: {} }

我希望"你好"打印在控制台上。

感谢任何帮助或指示。

我看到 2 个问题:

  1. t.eval 返回线程本身(从控制台输出中可以看到)。代码执行的结果将传递给回调(如果提供了回调)
  2. 您需要在传递给 eval 的代码中要求插件,闭包语义在这里不起作用。但看起来这是不可能的:需求不是在线程上下文中定义的。我认为这是为了防止竞争条件问题而设计的。另请参阅 https://github.com/audreyt/node-webworker-threads/issues/15