libuv线程通信

libuv thread communication

我有一个 C++ 库,客户端应用程序使用这个库从服务器查询数据。此库创建一个单独的线程与服务器通信,查询结果将作为参数传递给回调函数。

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

根据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.

这个警告是否意味着 uv_async_send 可能会导致数据丢失?我想知道 libuv 是否为这个问题提供了更好的解决方案,或者我应该使用其他一些 thead 库。

你是对的 - uv_async_send 是唤醒主线程的正确方法。我建议每次调用 uv_async_send 时,将回调的相关数据累积在队列或向量或其他一些容器中。正如文档中提到的,uv_async_send() 调用将被合并,并且回调事件将至少唤醒主线程一次。为了确保传递所有回调数据,您需要将其存储在队列或向量中的某个位置,以便您的 c++ 回调代码可以传递所有数据。

您也可以使用uv_callback

它使用队列处理非合并调用。

在接收线程中:

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);

在发件人线程中:

uv_callback_fire(&send_data, data, NULL);

我们甚至可以在其他线程上调用函数并异步(和同步)通知结果。