I'm trying to create a very little nodejs addons example. My c++ code is this:
void __sleep(uv_work_t* req) {
usleep(1000 * 1000 * 5); // = 5seconds
}
void after(uv_work_t *handle, int status) {
printf("After\n");
}
Handle<Value> foo(const Arguments& args) {
HandleScope scope;
uv_loop_t *loop = uv_default_loop();
uv_work_t req;
uv_queue_work(loop, &req, __sleep, after);
return scope.Close(Undefined());
}
void InitAll(Handle<Object> exports, Handle<Object> module) {
NODE_SET_METHOD(exports, "foo", foo);
}
NODE_MODULE("myModule", InitAll)
In js, this:
console.log(myModule);
myModule.foo();
console.log("started sleeping...");
When i call myModule.foo
function the process terminates with a segmentation fault.
I have tried to add uv_run(loop, UV_RUN_DEFAULT)
but this blocks the main thread.
Where did I go wrong? Thanks
The problem is that
req
is allocated on stack and is freed whenfoo
returns. You need to allocate it on heap (usingnew
ormalloc
) and free it manually when you are done (for example, inafter
callback)