Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uv_queue_work does not run callback_method in node addon (c++)

I am making a node addon in C++, and I want to be able to make callbacks from other threads. To try it, I'm making the following test using uv_queue_work and Nan. If I call the function Hello, it should start a new thread for the method firstMethod, and when it finishes, call the next method "callbackMethod" in another thread, where I would make a callback to Javascript. But for some reason, it runs the first method and it does not run the second.

This is my code.

void Hello(const v8::FunctionCallbackInfo<v8::Value>& args) {
    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    v8::HandleScope scope(isolate);
    v8::Local<v8::Function> callback;

    callback = args[0].As<v8::Function>();

    ListBaton* baton = new ListBaton();
    baton->callback = new Nan::Callback(callback);

    uv_work_t* req = new uv_work_t();
    req->data = baton;
    uv_queue_work(uv_default_loop(), req, firstMethod, callbackMethod);
}

void firstMethod(uv_work_t* req) {
    std::cout << "Entering PRE thread" << std::endl;
    sleep(1);
    std::cout << "Leaving PRE thread" << std::endl;
}

void callbackMethod(uv_work_t* req, int status) {
    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    v8::HandleScope scope(isolate);
    if(!isolate)
    {
        std::cout << "Isolate was null" << std::endl;
        isolate = v8::Isolate::New();
        isolate->Enter();
    }
    ListBaton* data = static_cast<ListBaton*>(req->data);

    v8::Local<v8::Value> argv[2] = {
            v8::Undefined(isolate),
            v8::String::NewFromUtf8(isolate,"WORLD")
    };


    std::cout << "Sending callback" << std::endl;
    data->callback->Call(2,argv);
}
void init (v8::Handle<v8::Object> target) {
    NODE_SET_METHOD(target, "hello", Hello);
}

NODE_MODULE(HelloNan, init);

If you guys could help me with this I would appreciate it a lot...

like image 993
Antirreni91 Avatar asked Aug 08 '26 04:08

Antirreni91


1 Answers

If it is actual try follow instead of your data->callback->Call(2,argv);

// execute the callback
Local<Function>::New(isolate, data->callback)->Call(isolate->GetCurrentContext()->Global(), 2, argv);

// Free up the persistent function callback
data->callback.Reset();

delete data;
like image 150
Kolibaba Sergey Avatar answered Aug 09 '26 17:08

Kolibaba Sergey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!