Question

I have created a web worker thread in my javascript code. I am trying to call a C++ function from the thread using node-gyp and V8. But I am unable to get it to work.

Here's the code for 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)

And here's the code for myhello.js

var addon = require('./build/Release/hello');
var thread = require('webworker-threads');

var t = thread.create();
console.log(t.eval("addon.hello()")); 

When I run node myhello.js I get the following output

{ 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: {} }

I expect "hello" to be printed on the console.

Appreciate any help or pointers.

Was it helpful?

Solution

I see 2 issues:

  1. t.eval returns thread itself (as you can see from console output). The result of code execution is passed to callback, if one is provided
  2. You need to require addon inside code you pass to eval, closure semantics doesn't work here. But it looks like this is impossible: require is not defined in threads context. I assume it's by design to prevent race condition issues. Also see https://github.com/audreyt/node-webworker-threads/issues/15
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top