gpt4 book ai didi

c++ - libuv线程通信

转载 作者:太空狗 更新时间:2023-10-29 20:56:22 27 4
gpt4 key购买 nike

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

现在我想将这个 c++ 库包装到 nodejs 本地模块,因为回调函数是在这个库自己的线程中调用的,为了将查询结果传递给 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 时,将回调的相关数据累积在队列、 vector 或其他容器中。正如文档中提到的,uv_async_send() 调用将被合并,并且回调事件将至少唤醒主线程一次。为了确保传递所有回调数据,您需要将其存储在队列或 vector 中的某个位置,以便您的 C++ 回调代码可以传递所有数据。

关于c++ - libuv线程通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33721277/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com