Search code examples
c++node.jsmultithreadinglibuv

How can I use uv_queue_work multiple times?


I am making a C++ addon for Node. And I would like to run uv_queue_work multiple times without having to sleep the main thread. Any idea of how to do this?

So far I've done this:

void main(const FunctionCallbackInfo<Value>& args) {
//here goes my main code

//Here I schedule the worker, to run BEFOREmethod in a new thread, and AFTERmethod in the main thread
uv_queue_work(uv_default_loop(), req, BEFOREmethod,(uv_after_work_cb) AFTERmethod);

return callback;
}



void BEFOREmethod(uv_work_t* req){

//here goes the code that runs in new thread
usleep(200000);
}




void AFTERmethod(uv_work_t* req, int status){

//here goes the code that runs in main thread

//Then we schedule the uv_queue_work again
uv_queue_work(uv_default_loop(), req, BEFOREmethod,(uv_after_work_cb) AFTERmethod);
}

So this works, I can re-schedule the uv_queue_work, but there is a memory leak, if I keep this running, memory usage keeps increasing. But I haven't found another way of doing this. So I would appreciate any help if anybody has an idea.


Solution

  • I found the solution! Apparently the worker releases memory by itself after the job is done, so I can keep doing it this way. The memory leak was my code's fault, since I was allocating memory and not releasing it somewhere else (totally hidden I didn't see it), but now it's solved.

    Thanks!