节点插件使用libuv和uv_async_send – 节点进程不会退出

我有一个要求从一个节点插件调用一个Javascript函数。 插件将有一个连续运行的后台线程,所以它不是使用async_queue_work的经典asynchronous工作者需求。 我认为uv_async_send在这种情况下更合适。 我想在节点事件循环中放置一个函数,只要节点是空闲的就执行。 这个函数应该在主节点线程中运行。

要开始我有一个非常简单的插件,我正在试验uv_queue_workuv_async_send 。 我可以同时工作,但在uv_async_send的情况下,节点进程永远不会退出。

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) 

产量

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

(这个过程不会退出)

完整的示例项目在这里: https : //github.com/jugglingcats/node-uv

任何帮助非常感谢。

问题是我没有叫uv_close ! 必须是简单的东西。

修正了callback方法

 static void Runner2(uv_async_t* handle) { printf("Got async send! %d\n", n++); uv_close((uv_handle_t *)handle, NULL); } 

相关文档: https : //nikhilm.github.io/uvbook/threads.html

修正了github项目: https : //github.com/jugglingcats/node-uv/tree/working