Search code examples
c++node.jsmultithreadinglibuvnode.js-addon

libuv thread communication


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.


Solution

  • 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.