I'm creating a node C++ addon that is supposed to call back a js function as events are triggered by some other thread that is not under my control (it is actually a .net thread from a managed dll I use). As the JS world is single-threaded, I can't just keep the js function reference around and call it from that non-js thread. I can't even create the parameters I want to pass to that callback function on that thread.
I've seen uv_queue_work
being used in cases where you want to move work off of the js thread and once finished and get called back from the js thread to do whatever you need to do on it, like e.g. calling back a js function.
For later reference, here's that function's signature:
int uv_queue_work(uv_loop_t* loop, uv_work_t* req, uv_work_cb work_cb,
uv_after_work_cb after_work_cb);
Calling uv_queue_work is fine for one-off jobs, and I could probably get it to call me arbitrarily often by chaining calls to uv_queue_work
from after_work_cb
, while work_cb
synchronizes with that other thread, but I wonder if there isn't a more straightforward way to do it.
Like a fn provided by node.js that could be called directly by any other thread with a fn pointer that points to code to be executed on the main js thread at the next occasion. Any idea?
As long as the callback code is purely sync than no two functions can execute parallel.
Node JS Platform does not follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded with Event Loop Model. Node JS Processing model mainly based on Javascript Event based model with Javascript callback mechanism.
NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications. Asynchronous here refers to all those functions in JavaScript that are processed in the background without blocking any other request.
Rather than using uv_queue_work, you should look at the uv_async_* functions (Check out https://github.com/joyent/libuv/blob/master/include/uv.h).
A very nice implementation of this can be found in the node sqllite project https://github.com/developmentseed/node-sqlite3/blob/master/src/async.h.
Just a note however, if you are not EXTREMELY careful with this stuff, you will end up with some TERRIBLE loop reference count bugs (Application exits to early, or not at all)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With