Search code examples
multithreadingasynchronouscallbacklibuv

Ensure asynchonous callback is called by libuv


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

So in case I need a guarantee that each time I make a call to uv_async_send() my callback gets called with the correct payload is it sufficient to have a distinct uv_async_t handle? For example, is it save to allocate a new uv_async_t on the heap, fill its data member, call uv_async_init and uv_async_send and in the processing callback close the handle using uv_close and then delete it? Does it matter which thread constructs the uv_async_t and which thread calls uv_async_init?

EDIT

  1. According to this discussion it does matter which thread calls uv_async_init.
  2. According to an answer to a previous question one has to take care to delete the uv_async_t only after the close callback passed to uv_close had been called.

Solution

  • You can do this by using a thread-safe queue and a single async handle. When you need a callback called, create some soft of structure to hold it, put it in the queue and call uv_async_send, then in the callback process the queue until it's empty.