I've been reading The libuv book, however the section on check and prepare watchers is incomplete so the only info i found was in uv.h:
/* * uv_prepare_t is a subclass of uv_handle_t. * * Every active prepare handle gets its callback called exactly once per loop * iteration, just before the system blocks to wait for completed i/o. */
and
/* * uv_check_t is a subclass of uv_handle_t. * * Every active check handle gets its callback called exactly once per loop * iteration, just after the system returns from blocking. */
I was wondering if there's any special usage of libuv's check and prepare watchers.
I'm writing a native node.js binding to a c++ library that needs to handle events fired from different threads, so naturally, the callbacks should be called from the main thread. I tried using uv_async_t
, however libuv does not guarantee that the callback will be invoked once per every uv_async_send
so this does not work for me.
That's why i decided to go with my own thread-safe event queue which i want to check periodically. So i was wondering whether using a check or prepare watcher will be ok for this purpose.
Actually, my current solution does use an uv_async_t
watcher - every time i receive an event, i put it in the queue and call uv_async_send
- so when the callback is finally invoked, i handle all events currently in the queue.
My concern with this approach is that many events might actually queue up until the callback is triggered and might get invalidated meanwhile (by invalidated, i mean it's become pointless to handle them at this point).
So i want to be able to check the event queue as frequently as possible - which check/prepare watchers can provide, but maybe it's an overkill to do it (and lock a mutex) on every event loop iteration?
And, more importantly, maybe they are supposed to serve some more special purpose than just securing once-per-loop-iteration callback invocation?
Thanks
You could use a prepare handle to check your queue for events, and a async handle just to wakeup the loop.
If you use only a prepare handle you could en up in the situation where the loop is blocked for i/o and nobody would process the queue until it finishes polling. The async handle would "wakeup" the loop, and the next time prepare handles run you'd process the queue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With