baichuan.he
baichuan.he

Reputation: 61

How to use libuv async handles in a thread-safe manner?

uv_async_send is thread-safe, but uv_async_init is not. If I use uv_async_init to create an async handle in the loop’s thread, I may call uv_async_send many times, but its callback will only be called once. I need the callback to be called the same number of times as I call uv_async_send.

But it's not safe when I create an async handle for each callback in another thread. So, how can I use libuv async handles in a thread-safe manner?

Upvotes: 1

Views: 1679

Answers (2)

baichuan.he
baichuan.he

Reputation: 61

  1. Create a single async handle in the loop's thread.
  2. Implement a thread-safe queue. (libuv doesn't expose one in its API, but it does expose primitives useful for creating one, e.g. uv_mutex_t)
  3. The other threads put an item in the thread-safe call and then immediately call uv_async_send.
  4. The async callback removes all pending items from the queue and processes them.

Upvotes: 2

Armali
Armali

Reputation: 19395

uv_async_init is not thread safe … it's not safe when i create async handle for each callback in other thread … i can creat a async handle in loop's thread

It appears you misunderstand the term thread safe. It does not mean that you may not call uv_async_init() from a thread other than the loop thread. It just means that you may not call it from multiple threads in parallel (without interlocking).

Upvotes: -1

Related Questions