确保 libuv 调用异步回调

Ensure asynchonous callback is called by libuv

documentation of libuv states:

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() 时,我的回调都会使用正确的有效负载调用,那么拥有一个不同的 uv_async_t 句柄就足够了吗?例如,是否保存在堆上分配一个新的 uv_async_t,填充其 data 成员,调用 uv_async_inituv_async_send 并在处理回调中使用 uv_close然后删除呢?哪个线程构造 uv_async_t 和哪个线程调用 uv_async_init 重要吗?

编辑

  1. 根据 this discussion确实 影响哪个线程调用 uv_async_init
  2. 根据 的说法,只有在调用了传递给 uv_close 的关闭回调后,才需要注意删除 uv_async_t

您可以使用线程安全队列和单个异步句柄来完成此操作。当您需要调用回调时,创建一些软结构来保存它,将其放入队列并调用 uv_async_send,然后在回调中处理队列直到它为空。