I have a c++ lib, client application use this lib to query data from server. This lib create a seperate thread to communicate with server, query result will be passed as parameters in callback function.
Now i want to wrap this c++ lib to nodejs native module, since callback functions are called in this lib's own thread, in order to pass query result to js environment, i believe i have to use libuv's uv_async_send(uv_async_t* async) method to pass data between two thread.(correct me if I'm wrong)
According to libuv's doc:
Warning: libuv will coalesce calls to uv_async_send(), that is, not every call to it will yield an execution of the callback. For example: if uv_async_send() is called 5 times in a row before the callback is called, the callback will only be called once. If uv_async_send() is called again after the callback was called, it will be called again.
Does this warning means uv_async_send may cause data lost? I want to know whether the libuv offer a better solution for this problem or should I use some other thead librarys.
You are correct- uv_async_send
is the correct way to wake the main thread. I recommend that every time you call uv_async_send
, you accumulate the related data for the callback in a queue or vector or some other container. As the documentation mentions, uv_async_send() calls will be coalesced, and the callback event will wake the main thread at least once. In order to make sure that all of your callback data is delivered, you will want to store it somewhere in a queue or vector so that your c++ callback code can deliver it all.
You can also use uv_callback.
It handles non-coalescing calls using queues.
In the receiver thread:
uv_callback_t send_data;
void * on_data(uv_callback_t *handle, void *data) {
do_something(data);
free(data);
}
uv_callback_init(loop, &send_data, on_data, UV_DEFAULT);
In the sender thread:
uv_callback_fire(&send_data, data, NULL);
We can even call functions on other threads and get notified with the result asynchronously (and synchronously).
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