Question

I'm writing a native node module in C++ which will be a binding for a C library.

Some of the objects in this library must only be used by a single thread. Which means that if I use uv_queue_work I can't make sure they are only used by the same thread, since - as far as I know - libuv uses a thread pool and I haven't been able to find out how to tell it what thread to use for this kind of work.

Here are some ideas for the situation, but I'm not sure which is the correct approach.

  • Simply make all the methods synchronous - this would unfortunately beat the purpose and concepts of node, so I'd prefer not to
  • Create a custom thread and execute my code on that - this would defeat the purpose of libuv's thread pool and require more work
  • Tell libuv somehow to execute operations of the same object on the same thread in its thread pool - I haven't found a way in the documentation to do this

What is the recommended course of action for this kind of Node.js module?

Was it helpful?

Solution

While I'll start by saying it's unfortunate that the architecture doesn't support the generic callback model, I'll accept it is a special case that cannot be avoided.

You still have full access to the libuv API in a native module, so it's entirely possible to create your own thread use that single thread to schedule all the applicable asynchronous work. For a quick primer check out http://nikhilm.github.io/uvbook/threads.html

After the operation is complete you can pass the desired js callback to MakeCallback. This should allow any js API interactions appear normal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top