In the node native module, how can I make sure my asynchronous code always runs on the same thread?

I am writing my own node module in C ++, which will be a binding for the C library.

Some of the objects in this library should be used by only one thread . This means that if I use uv_queue_work , I canโ€™t make sure that they are used only by the same thread, since, as far as I know, libuv uses the thread pool, and I could not find out how to tell which thread to use for this kind works.

Here are some ideas for the situation, but I'm not sure if this is the right approach.

  • Just make all methods synchronous - this, unfortunately, will surpass the goals and concepts of node, so I would rather not
  • Create your own thread and execute my code on this - this will hit the target of the libuv thread pool and will require more work.
  • Tell libuv to somehow perform the operations of the same object in the same thread in the thread pool - I did not find a way in the documentation to do this

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

+4
source share
1 answer

While I begin by regretting that architecture does not support a common callback model, I agree that this is a special case that cannot be avoided.

You still have full access to the libuv API in your own module, so itโ€™s entirely possible to create your own thread that uses one thread to schedule all applicable asynchronous work. For a quick look at the primer http://nikhilm.imtqy.com/uvbook/threads.html

After the operation is completed, you can pass the desired js response to MakeCallback . This should make any js API interaction look normal.

+2
source

Source: https://habr.com/ru/post/1479433/


All Articles