Friday, 12 May 2017

Node addon using libuv and uv_async_send -- node process doesn't exit

I have a requirement to invoke a Javascript function from a node addon. The addon will have a background thread that runs continuously, so it's not quite the classic async worker requirement using async_queue_work. I think uv_async_send is more appropriate in this scenario. I want to place a function on the node event loop to be executed as soon as node is free. This function should run in the main node thread.

To get started I have a very simple addon and I'm experimenting with uv_queue_work vs uv_async_send. I can get both to work but in the case of uv_async_send, the node process never exits.

node-uv.cc

#include <node.h>
#include <uv.h>

using namespace v8;

static void Runner(uv_work_t *req)
{
    printf("Async work running!\n");
}

static void RunDone(uv_work_t *req, int status)
{
    delete req;
    printf("Async work done!\n");
}

static void Runner2(uv_async_t* handle) {
    printf("Got async send!\n");
}

void Start(const FunctionCallbackInfo<Value>& args)
{
    printf("In run async\n");

    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    uv_work_t *req = (uv_work_t*)malloc(sizeof(uv_work_t));

    /// Example using uv_queue_work (working fine)
    printf("Queue work\n");
    uv_queue_work(uv_default_loop(), req, &Runner, &RunDone);

    uv_async_t *handle = (uv_async_t*)malloc(sizeof(uv_async_t));
    uv_async_init(uv_default_loop(), handle, &Runner2);

    /// Example using uv_async_send (node does not terminate)
    printf("Async send\n");
    uv_async_send(handle);
}

void Init(Handle<Object> exports, Handle<Object> module)
{
    NODE_SET_METHOD(exports, "start", Start);
}

NODE_MODULE(node_uv, Init)

output

$ node test
calling addon
In run async
Queue work
Async send
Async work running!
called addon
Got async send!
Async work done!

(process doesn't quit at this point)

The full example project is here: https://github.com/jugglingcats/node-uv

Any help much appreciated.



via jugglingcats

No comments:

Post a Comment