Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js C++ addon: Multiple callbacks from different thread

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?

like image 385
Evgeniy Berezovsky Avatar asked Jul 09 '12 07:07

Evgeniy Berezovsky


People also ask

How many callback functions can be executed at any time?

As long as the callback code is purely sync than no two functions can execute parallel.

Is NodeJS single threaded or multithreaded?

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.

Is NodeJS synchronous or asynchronous?

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.


1 Answers

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)

like image 135
major-mann Avatar answered Sep 30 '22 15:09

major-mann