1

I'm writing an add-on for node.js using c++.

here some snippets:

class Client : public node::ObjectWrap, public someObjectObserver {
public:
  void onAsyncMethodEnds() {
    Local<Value> argv[] = { Local<Value>::New(String::New("TheString")) };
    this->callback->Call(Context::GetCurrent()->Global(), 1, argv);
  }
....
private:
  static v8::Handle<v8::Value> BeInitiator(const v8::Arguments& args) {
    HandleScope scope;
    Client* client = ObjectWrap::Unwrap<Client>(args.This());

    client->someObject->asyncMethod(client, NULL);

    return scope.Close(Boolean::New(true));        
  }      

  static v8::Handle<v8::Value> SetCallback(const v8::Arguments& args) {
    HandleScope scope;
    Client* client = ObjectWrap::Unwrap<Client>(args.This());
    client->callback = Persistent<Function>::New(Handle<Function>::Cast(args[0]));

    return scope.Close(Boolean::New(true));
  }

I need to save a javascript function as callback to call it later. The Client class is an observer for another object and the javascript callback should be called from onAsyncMethodEnds. Unfortunately when I call the function "BeInitiator" I receive "Bus error: 10" error just before the callback Call()

thanks in advice

2
  • Are you calling it in the same thread? Commented Jun 12, 2013 at 23:59
  • No.. The "asyncmethod" starts a new thread. This method is part of a lib that I've linked that uses talk_base/thread in order to run asynchronous operations. Commented Jun 13, 2013 at 5:40

1 Answer 1

3

You cannot ->Call from another thread. JavaScript and Node are single threaded and attempting to call a function from another thread amounts to trying to run two threads of JS at once.

You should either re-work your code to not do that, or you should read up on libuv's threading library. It provides uv_async_send which can be used to trigger callback in the main JS loop from a separate thread.

There are docs here: http://nikhilm.github.io/uvbook/threads.html

Sign up to request clarification or add additional context in comments.

5 Comments

I suppose that this resolves the problem. Unfortunately I can't use libuv.. I will try to do the same thing using the Send method of talk_base/thread. Thanks a lot!
Why can't you use libuv?
I ask only because you should have access to it automatically if you are compiling for Node.
Because the thread was run by an external library that I have linked in to the project. However I have found that uv_send and uv_init work also within "not libuv thread". So thank you.
Here is a full example blog.scottfrees.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.