简体   繁体   English

libuv线程通信

[英]libuv thread communication

I have a c++ lib, client application use this lib to query data from server. 我有一个c ++ lib,客户端应用程序使用这个lib来查询来自服务器的数据。 This lib create a seperate thread to communicate with server, query result will be passed as parameters in callback function. 这个lib创建一个单独的线程与服务器通信,查询结果将作为参数传递给回调函数。

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) 现在我想将这个c ++ lib包装到nodejs本机模块,因为在这个lib自己的线程中调用了回调函数,为了将查询结果传递给js环境,我相信我必须使用libuv的uv_async_send(uv_async_t * async)方法来传递两个线程之间的数据。(如果我错了,请纠正我)

According to libuv's doc : 根据libuv的文档

Warning: libuv will coalesce calls to uv_async_send(), that is, not every call to it will yield an execution of the callback. 警告:libuv将合并对uv_async_send()的调用,也就是说,并非每次调用都会产生回调执行。 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. 例如:如果在调用回调之前连续5次调用uv_async_send(),则回调将只调用一次。 If uv_async_send() is called again after the callback was called, it will be called again. 如果在调用回调后再次调用uv_async_send(),则会再次调用它。

Does this warning means uv_async_send may cause data lost? 此警告是否意味着uv_async_send可能导致数据丢失? I want to know whether the libuv offer a better solution for this problem or should I use some other thead librarys. 我想知道libuv是否为这个问题提供了更好的解决方案,还是应该使用其他一些thead图书馆。

You are correct- uv_async_send is the correct way to wake the main thread. 你是对的 - uv_async_send是唤醒主线程的正确方法。 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. 我建议每次调用uv_async_send ,都会在队列或向量或其他容器中累积回调的相关数据。 As the documentation mentions, uv_async_send() calls will be coalesced, and the callback event will wake the main thread at least once. 正如文档中提到的,uv_async_send()调用将被合并,并且回调事件将至少唤醒主线程一次。 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. 为了确保传递所有回调数据,您需要将其存储在队列或向量中的某个位置,以便您的c ++回调代码可以提供所有这些。

You can also use uv_callback . 您也可以使用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). 我们甚至可以在其他线程上调用函数,并异步(并同步)获得结果通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM