1 #ifndef DASYNQ_H_INCLUDED
2 #define DASYNQ_H_INCLUDED
4 #include "dasynq-config.h"
6 #include "dasynq-flags.h"
7 #include "dasynq-stableheap.h"
8 #include "dasynq-interrupt.h"
9 #include "dasynq-util.h"
11 // Dasynq uses a "mix-in" pattern to produce an event loop implementation incorporating selectable implementations of
12 // various components (main backend, timers, child process watch mechanism etc). In C++ this can be achieved by
13 // a template for some component which extends its own type parameter:
15 // template <typename Base> class X : public B { .... }
17 // We can chain several such components together (and so so below) to "mix in" the functionality of each into the final
20 // template <typename T> using Loop = epoll_loop<interrupt_channel<timer_fd_events<child_proc_events<T>>>>;
22 // (which defines an alias template "Loop", whose implementation will use the epoll backend, a standard interrupt channel
23 // implementation, a timerfd-based timer implementation, and the standard child process watch implementation).
24 // We sometimes need the base class to be able to call derived-class members: to do this we pass a reference to
25 // the derived instance into a templated method in the base, called "init":
27 // template <typename T> void init(T *derived)
29 // // can call method on derived:
30 // derived->add_listener();
31 // // chain to next class:
32 // Base::init(derived);
35 // At the base all this is the event_dispatch class, defined below, which receives event notifications and inserts
36 // them into a queue for processing. The event_loop class, also below, wraps this (via composition) in an interface
37 // which can be used to register/de-regsiter/enable/disable event watchers, and which can process the queued events
38 // by calling the watcher callbacks. The event_loop class also provides some synchronisation to ensure thread-safety.
40 #if DASYNQ_HAVE_KQUEUE
41 #include "dasynq-kqueue.h"
43 #include "dasynq-posixtimer.h"
45 template <typename T> using timer_events = posix_timer_events<T>;
48 #include "dasynq-itimer.h"
50 template <typename T> using timer_events = itimer_events<T>;
53 #include "dasynq-childproc.h"
55 template <typename T> using loop_t = kqueue_loop<interrupt_channel<timer_events<child_proc_events<T>>>>;
56 using loop_traits_t = kqueue_traits;
58 #elif DASYNQ_HAVE_EPOLL
59 #include "dasynq-epoll.h"
60 #include "dasynq-timerfd.h"
61 #include "dasynq-childproc.h"
63 template <typename T> using loop_t = epoll_loop<interrupt_channel<timer_fd_events<child_proc_events<T>>>>;
64 using loop_traits_t = epoll_traits;
67 #error No loop backened defined - see dasynq-config.h
71 #include <condition_variable>
74 #include <system_error>
79 #include "dasynq-mutex.h"
81 #include "dasynq-basewatchers.h"
86 * Values for rearm/disarm return from event handlers
90 /** Re-arm the event watcher so that it receives further events */
92 /** Disarm the event watcher so that it receives no further events, until it is re-armed explicitly */
94 /** Leave in current armed/disarmed state */
96 /** Remove the event watcher (and call "removed" callback) */
98 /** The watcher has been removed - don't touch it! */
100 /** RE-queue the watcher to have its notification called again */
106 // Classes for implementing a fair(ish) wait queue.
107 // A queue node can be signalled when it reaches the head of
110 template <typename T_Mutex> class waitqueue;
111 template <typename T_Mutex> class waitqueue_node;
113 // Select an appropriate condition variable type for a mutex:
114 // condition_variable if mutex is std::mutex, or condition_variable_any
116 template <class T_Mutex> class condvar_selector;
118 template <> class condvar_selector<std::mutex>
121 typedef std::condition_variable condvar;
124 template <class T_Mutex> class condvar_selector
127 typedef std::condition_variable_any condvar;
130 template <> class waitqueue_node<null_mutex>
132 // Specialised waitqueue_node for null_mutex.
133 friend class waitqueue<null_mutex>;
136 void wait(std::unique_lock<null_mutex> &ul) { }
142 template <typename T_Mutex> class waitqueue_node
144 typename condvar_selector<T_Mutex>::condvar condvar;
145 friend class waitqueue<T_Mutex>;
147 // ptr to next node in queue, set to null when added to queue tail:
148 waitqueue_node * next;
153 condvar.notify_one();
156 void wait(std::unique_lock<T_Mutex> &mutex_lock)
158 condvar.wait(mutex_lock);
162 template <> class waitqueue<null_mutex>
165 // remove current head of queue, return new head:
166 waitqueue_node<null_mutex> * unqueue()
171 waitqueue_node<null_mutex> * get_head()
176 bool check_head(waitqueue_node<null_mutex> &node)
186 void queue(waitqueue_node<null_mutex> *node)
191 template <typename T_Mutex> class waitqueue
193 waitqueue_node<T_Mutex> * tail = nullptr;
194 waitqueue_node<T_Mutex> * head = nullptr;
197 // remove current head of queue, return new head:
198 waitqueue_node<T_Mutex> * unqueue()
201 if (head == nullptr) {
207 waitqueue_node<T_Mutex> * get_head()
212 bool check_head(waitqueue_node<T_Mutex> &node)
214 return head == &node;
219 return head == nullptr;
222 void queue(waitqueue_node<T_Mutex> *node)
224 node->next = nullptr;
235 // Do standard post-dispatch processing for a watcher. This handles the case of removing or
236 // re-queing watchers depending on the rearm type.
237 template <typename Loop> void post_dispatch(Loop &loop, base_watcher *watcher, rearm rearm_type)
239 if (rearm_type == rearm::REMOVE) {
240 loop.get_base_lock().unlock();
241 watcher->watch_removed();
242 loop.get_base_lock().lock();
244 else if (rearm_type == rearm::REQUEUE) {
245 loop.requeue_watcher(watcher);
249 // This class serves as the base class (mixin) for the AEN mechanism class.
251 // The event_dispatch class maintains the queued event data structures. It inserts watchers
252 // into the queue when events are received (receiveXXX methods). It also owns a mutex used
253 // to protect those structures.
255 // In general the methods should be called with lock held. In practice this means that the
256 // event loop backend implementations must obtain the lock; they are also free to use it to
257 // protect their own internal data structures.
258 template <typename T_Mutex, typename Traits, typename LoopTraits> class event_dispatch
260 friend class dasynq::event_loop<T_Mutex, LoopTraits>;;
263 using mutex_t = T_Mutex;
264 using traits_t = Traits;
268 // queue data structure/pointer
269 prio_queue event_queue;
271 using base_signal_watcher = dasynq::dprivate::base_signal_watcher<mutex_t, typename traits_t::sigdata_t>;
272 using base_fd_watcher = dasynq::dprivate::base_fd_watcher<mutex_t>;
273 using base_bidi_fd_watcher = dasynq::dprivate::base_bidi_fd_watcher<mutex_t>;
274 using base_child_watcher = dasynq::dprivate::base_child_watcher<mutex_t>;
275 using base_timer_watcher = dasynq::dprivate::base_timer_watcher<mutex_t>;
277 // Add a watcher into the queueing system (but don't queue it). Call with lock held.
278 // may throw: std::bad_alloc
279 void prepare_watcher(base_watcher *bwatcher)
281 event_queue.allocate(bwatcher->heap_handle, bwatcher);
284 void queue_watcher(base_watcher *bwatcher) noexcept
286 event_queue.insert(bwatcher->heap_handle, bwatcher->priority);
289 void dequeue_watcher(base_watcher *bwatcher) noexcept
291 if (event_queue.is_queued(bwatcher->heap_handle)) {
292 event_queue.remove(bwatcher->heap_handle);
296 // Remove watcher from the queueing system
297 void release_watcher(base_watcher *bwatcher) noexcept
299 event_queue.deallocate(bwatcher->heap_handle);
305 template <typename T> void init(T *loop) noexcept { }
307 void sigmaskf(int how, const sigset_t *set, sigset_t *oset)
309 LoopTraits::sigmaskf(how, set, oset);
312 // Receive a signal; return true to disable signal watch or false to leave enabled.
313 // Called with lock held.
314 template <typename T>
315 bool receive_signal(T &loop_mech, typename Traits::sigdata_t & siginfo, void * userdata) noexcept
317 base_signal_watcher * bwatcher = static_cast<base_signal_watcher *>(userdata);
318 bwatcher->siginfo = siginfo;
319 queue_watcher(bwatcher);
323 template <typename T>
324 void receive_fd_event(T &loop_mech, typename Traits::fd_r fd_r, void * userdata, int flags) noexcept
326 base_fd_watcher * bfdw = static_cast<base_fd_watcher *>(userdata);
328 bfdw->event_flags |= flags;
330 base_watcher * bwatcher = bfdw;
332 bool is_multi_watch = bfdw->watch_flags & multi_watch;
333 if (is_multi_watch) {
334 base_bidi_fd_watcher *bbdw = static_cast<base_bidi_fd_watcher *>(bwatcher);
335 bbdw->watch_flags &= ~flags;
336 if ((flags & IN_EVENTS) && (flags & OUT_EVENTS)) {
337 // Queue the secondary watcher first:
338 queue_watcher(&bbdw->out_watcher);
340 else if (flags & OUT_EVENTS) {
341 // Use the secondary watcher for queueing:
342 bwatcher = &(bbdw->out_watcher);
346 queue_watcher(bwatcher);
348 if (! traits_t::has_separate_rw_fd_watches) {
349 // If this is a bidirectional fd-watch, it has been disabled in *both* directions
350 // as the event was delivered. However, the other direction should not be disabled
351 // yet, so we need to re-enable:
352 int in_out_mask = IN_EVENTS | OUT_EVENTS;
353 if (is_multi_watch && (bfdw->watch_flags & in_out_mask) != 0) {
354 // We need to re-enable the other channel now:
355 loop_mech.enable_fd_watch_nolock(bfdw->watch_fd, userdata,
356 (bfdw->watch_flags & in_out_mask) | ONE_SHOT);
361 // Child process terminated. Called with both the main lock and the reaper lock held.
362 void receive_child_stat(pid_t child, int status, void * userdata) noexcept
364 base_child_watcher * watcher = static_cast<base_child_watcher *>(userdata);
365 watcher->child_status = status;
366 watcher->child_termd = true;
367 queue_watcher(watcher);
370 void receive_timer_expiry(timer_handle_t & timer_handle, void * userdata, int intervals) noexcept
372 base_timer_watcher * watcher = static_cast<base_timer_watcher *>(userdata);
373 watcher->intervals += intervals;
374 queue_watcher(watcher);
377 // Pull a single event from the queue; returns nullptr if the queue is empty.
378 // Call with lock held.
379 base_watcher * pull_event() noexcept
381 if (event_queue.empty()) {
385 auto & rhndl = event_queue.get_root();
386 base_watcher *r = event_queue.node_data(rhndl);
387 event_queue.pull_root();
391 // Queue a watcher for reomval, or issue "removed" callback to it.
392 // Call with lock free.
393 void issue_delete(base_watcher *watcher) noexcept
395 // This is only called when the attention lock is held, so if the watcher is not
396 // active/queued now, it cannot become active (and will not be reported with an event)
397 // during execution of this function.
401 if (watcher->active) {
402 // If the watcher is active, set deleteme true; the watcher will be removed
403 // at the end of current processing (i.e. when active is set false).
404 watcher->deleteme = true;
405 release_watcher(watcher);
409 // Actually do the delete.
410 dequeue_watcher(watcher);
411 release_watcher(watcher);
414 watcher->watch_removed();
418 // Queue a watcher for reomval, or issue "removed" callback to it.
419 // Call with lock free.
420 void issue_delete(base_bidi_fd_watcher *watcher) noexcept
424 if (watcher->active) {
425 watcher->deleteme = true;
426 release_watcher(watcher);
429 dequeue_watcher(watcher);
430 release_watcher(watcher);
431 watcher->read_removed = true;
434 base_watcher *secondary = &(watcher->out_watcher);
435 if (secondary->active) {
436 secondary->deleteme = true;
437 release_watcher(watcher);
440 dequeue_watcher(secondary);
441 release_watcher(watcher);
442 watcher->write_removed = true;
445 if (watcher->read_removed && watcher->write_removed) {
447 watcher->watch_removed();
455 event_dispatch(const event_dispatch &) = delete;
459 // This is the main event_loop implementation. It serves as an interface to the event loop
460 // backend (of which it maintains an internal instance). It also serialises waits the backend
461 // and provides safe deletion of watchers (see comments inline).
462 template <typename T_Mutex, typename Traits>
465 using my_event_loop_t = event_loop<T_Mutex, Traits>;
466 friend class dprivate::fd_watcher<my_event_loop_t>;
467 friend class dprivate::bidi_fd_watcher<my_event_loop_t>;
468 friend class dprivate::signal_watcher<my_event_loop_t>;
469 friend class dprivate::child_proc_watcher<my_event_loop_t>;
470 friend class dprivate::timer<my_event_loop_t>;
472 friend void dprivate::post_dispatch<my_event_loop_t>(my_event_loop_t &loop,
473 dprivate::base_watcher *watcher, rearm rearm_type);
475 template <typename, typename> friend class dprivate::fd_watcher_impl;
476 template <typename, typename> friend class dprivate::bidi_fd_watcher_impl;
477 template <typename, typename> friend class dprivate::signal_watcher_impl;
478 template <typename, typename> friend class dprivate::child_proc_watcher_impl;
479 template <typename, typename> friend class dprivate::timer_impl;
481 using backend_traits_t = typename Traits::backend_traits_t;
483 template <typename T, typename U> using event_dispatch = dprivate::event_dispatch<T,U,Traits>;
484 using loop_mech_t = typename Traits::template backend_t<event_dispatch<T_Mutex, backend_traits_t>>;
485 using reaper_mutex_t = typename loop_mech_t::reaper_mutex_t;
488 using traits_t = Traits;
489 using loop_traits_t = typename loop_mech_t::traits_t;
490 using mutex_t = T_Mutex;
493 template <typename T> using waitqueue = dprivate::waitqueue<T>;
494 template <typename T> using waitqueue_node = dprivate::waitqueue_node<T>;
495 using base_watcher = dprivate::base_watcher;
496 using base_signal_watcher = dprivate::base_signal_watcher<T_Mutex, typename loop_traits_t::sigdata_t>;
497 using base_fd_watcher = dprivate::base_fd_watcher<T_Mutex>;
498 using base_bidi_fd_watcher = dprivate::base_bidi_fd_watcher<T_Mutex>;
499 using base_child_watcher = dprivate::base_child_watcher<T_Mutex>;
500 using base_timer_watcher = dprivate::base_timer_watcher<T_Mutex>;
501 using watch_type_t = dprivate::watch_type_t;
503 loop_mech_t loop_mech;
505 // There is a complex problem with most asynchronous event notification mechanisms
506 // when used in a multi-threaded environment. Generally, a file descriptor or other
507 // event type that we are watching will be associated with some data used to manage
508 // that event source. For example a web server needs to maintain information about
509 // each client connection, such as the state of the connection (what protocol version
510 // has been negotiated, etc; if a transfer is taking place, what file is being
513 // However, sometimes we want to remove an event source (eg webserver wants to drop
514 // a connection) and delete the associated data. The problem here is that it is
515 // difficult to be sure when it is ok to actually remove the data, since when
516 // requesting to unwatch the source in one thread it is still possible that an
517 // event from that source is just being reported to another thread (in which case
518 // the data will be needed).
520 // To solve that, we:
521 // - allow only one thread to poll for events at a time, using a lock
522 // - use the same lock to prevent polling, if we want to unwatch an event source
523 // - generate an event to interrupt any polling that may already be occurring in
525 // - mark handlers as active if they are currently executing, and
526 // - when removing an active handler, simply set a flag which causes it to be
527 // removed once the current processing is finished, rather than removing it
530 // In particular the lock mechanism for preventing multiple threads polling and
531 // for allowing polling to be interrupted is tricky. We can't use a simple mutex
532 // since there is significant chance that it will be highly contended and there
533 // are no guarantees that its acquisition will be fair. In particular, we don't
534 // want a thread that is trying to unwatch a source being starved while another
535 // thread polls the event source.
537 // So, we use two wait queues protected by a single mutex. The "attn_waitqueue"
538 // (attention queue) is the high-priority queue, used for threads wanting to
539 // unwatch event sources. The "wait_waitquueue" is the queue used by threads
540 // that wish to actually poll for events.
541 // - The head of the "attn_waitqueue" is always the holder of the lock
542 // - Therefore, a poll-waiter must be moved from the wait_waitqueue to the
543 // attn_waitqueue to actually gain the lock. This is only done if the
544 // attn_waitqueue is otherwise empty.
545 // - The mutex only protects manipulation of the wait queues, and so should not
546 // be highly contended.
548 mutex_t wait_lock; // wait lock, used to prevent multiple threads from waiting
549 // on the event queue simultaneously.
550 waitqueue<mutex_t> attn_waitqueue;
551 waitqueue<mutex_t> wait_waitqueue;
553 mutex_t &get_base_lock() noexcept
555 return loop_mech.lock;
558 reaper_mutex_t &get_reaper_lock() noexcept
560 return loop_mech.get_reaper_lock();
563 void register_signal(base_signal_watcher *callBack, int signo)
565 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
566 std::lock_guard<mutex_t> guard(ed.lock);
568 loop_mech.prepare_watcher(callBack);
570 loop_mech.add_signal_watch_nolock(signo, callBack);
573 loop_mech.release_watcher(callBack);
578 void deregister(base_signal_watcher *callBack, int signo) noexcept
580 loop_mech.remove_signal_watch(signo);
582 waitqueue_node<T_Mutex> qnode;
583 get_attn_lock(qnode);
585 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
586 ed.issue_delete(callBack);
591 void register_fd(base_fd_watcher *callback, int fd, int eventmask, bool enabled, bool emulate = false)
593 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
594 std::lock_guard<mutex_t> guard(ed.lock);
596 loop_mech.prepare_watcher(callback);
599 if (! loop_mech.add_fd_watch(fd, callback, eventmask | ONE_SHOT, enabled, emulate)) {
600 callback->emulatefd = true;
601 callback->emulate_enabled = enabled;
603 callback->event_flags = eventmask & IO_EVENTS;
604 if (eventmask & IO_EVENTS) {
605 requeue_watcher(callback);
611 loop_mech.release_watcher(callback);
616 void register_fd(base_bidi_fd_watcher *callback, int fd, int eventmask, bool emulate = false)
618 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
619 std::lock_guard<mutex_t> guard(ed.lock);
621 loop_mech.prepare_watcher(callback);
623 loop_mech.prepare_watcher(&callback->out_watcher);
625 if (backend_traits_t::has_separate_rw_fd_watches) {
626 int r = loop_mech.add_bidi_fd_watch(fd, callback, eventmask | ONE_SHOT, emulate);
628 callback->emulatefd = true;
629 if (eventmask & IN_EVENTS) {
630 requeue_watcher(callback);
633 if (r & OUT_EVENTS) {
634 callback->out_watcher.emulatefd = true;
635 if (eventmask & OUT_EVENTS) {
636 requeue_watcher(&callback->out_watcher);
641 if (! loop_mech.add_fd_watch(fd, callback, eventmask | ONE_SHOT, true, emulate)) {
642 callback->emulatefd = true;
643 callback->out_watcher.emulatefd = true;
644 if (eventmask & IN_EVENTS) {
645 requeue_watcher(callback);
647 if (eventmask & OUT_EVENTS) {
648 requeue_watcher(&callback->out_watcher);
654 loop_mech.release_watcher(&callback->out_watcher);
659 loop_mech.release_watcher(callback);
664 void set_fd_enabled(base_watcher *watcher, int fd, int watch_flags, bool enabled) noexcept
667 loop_mech.enable_fd_watch(fd, watcher, watch_flags | ONE_SHOT);
670 loop_mech.disable_fd_watch(fd, watch_flags);
674 void set_fd_enabled_nolock(base_watcher *watcher, int fd, int watch_flags, bool enabled) noexcept
677 loop_mech.enable_fd_watch_nolock(fd, watcher, watch_flags | ONE_SHOT);
680 loop_mech.disable_fd_watch_nolock(fd, watch_flags);
684 void deregister(base_fd_watcher *callback, int fd) noexcept
686 if (callback->emulatefd) {
687 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
688 ed.issue_delete(callback);
692 loop_mech.remove_fd_watch(fd, callback->watch_flags);
694 waitqueue_node<T_Mutex> qnode;
695 get_attn_lock(qnode);
697 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
698 ed.issue_delete(callback);
703 void deregister(base_bidi_fd_watcher *callback, int fd) noexcept
705 if (backend_traits_t::has_separate_rw_fd_watches) {
706 loop_mech.remove_bidi_fd_watch(fd);
709 loop_mech.remove_fd_watch(fd, callback->watch_flags);
712 waitqueue_node<T_Mutex> qnode;
713 get_attn_lock(qnode);
715 event_dispatch<T_Mutex, backend_traits_t> & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
716 ed.issue_delete(callback);
721 void reserve_child_watch(base_child_watcher *callback)
723 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
724 std::lock_guard<mutex_t> guard(ed.lock);
726 loop_mech.prepare_watcher(callback);
728 loop_mech.reserve_child_watch_nolock(callback->watch_handle);
731 loop_mech.release_watcher(callback);
736 void unreserve(base_child_watcher *callback) noexcept
738 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
739 std::lock_guard<mutex_t> guard(ed.lock);
741 loop_mech.unreserve_child_watch(callback->watch_handle);
742 loop_mech.release_watcher(callback);
745 void register_child(base_child_watcher *callback, pid_t child)
747 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
748 std::lock_guard<mutex_t> guard(ed.lock);
750 loop_mech.prepare_watcher(callback);
752 loop_mech.add_child_watch_nolock(callback->watch_handle, child, callback);
755 loop_mech.release_watcher(callback);
760 void register_reserved_child(base_child_watcher *callback, pid_t child) noexcept
762 loop_mech.add_reserved_child_watch(callback->watch_handle, child, callback);
765 void register_reserved_child_nolock(base_child_watcher *callback, pid_t child) noexcept
767 loop_mech.add_reserved_child_watch_nolock(callback->watch_handle, child, callback);
770 void deregister(base_child_watcher *callback, pid_t child) noexcept
772 loop_mech.remove_child_watch(callback->watch_handle);
774 waitqueue_node<T_Mutex> qnode;
775 get_attn_lock(qnode);
777 event_dispatch<T_Mutex, backend_traits_t> & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
778 ed.issue_delete(callback);
783 // Stop watching a child process, but retain watch reservation so that another child can be
784 // watched without running into resource allocation issues.
785 void stop_watch(base_child_watcher *callback) noexcept
787 loop_mech.stop_child_watch(callback->watch_handle);
790 void register_timer(base_timer_watcher *callback, clock_type clock)
792 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
793 std::lock_guard<mutex_t> guard(ed.lock);
795 loop_mech.prepare_watcher(callback);
797 loop_mech.add_timer_nolock(callback->timer_handle, callback, clock);
800 loop_mech.release_watcher(callback);
804 void set_timer(base_timer_watcher *callBack, const timespec &timeout, clock_type clock) noexcept
806 struct timespec interval {0, 0};
807 loop_mech.set_timer(callBack->timer_handle, timeout, interval, true, clock);
810 void set_timer(base_timer_watcher *callBack, const timespec &timeout, const timespec &interval,
811 clock_type clock) noexcept
813 loop_mech.set_timer(callBack->timer_handle, timeout, interval, true, clock);
816 void set_timer_rel(base_timer_watcher *callBack, const timespec &timeout, clock_type clock) noexcept
818 struct timespec interval {0, 0};
819 loop_mech.set_timer_rel(callBack->timer_handle, timeout, interval, true, clock);
822 void set_timer_rel(base_timer_watcher *callBack, const timespec &timeout,
823 const timespec &interval, clock_type clock) noexcept
825 loop_mech.set_timer_rel(callBack->timer_handle, timeout, interval, true, clock);
828 void set_timer_enabled(base_timer_watcher *callback, clock_type clock, bool enabled) noexcept
830 loop_mech.enable_timer(callback->timer_handle, enabled, clock);
833 void set_timer_enabled_nolock(base_timer_watcher *callback, clock_type clock, bool enabled) noexcept
835 loop_mech.enable_timer_nolock(callback->timer_handle, enabled, clock);
838 void stop_timer(base_timer_watcher *callback, clock_type clock) noexcept
840 loop_mech.stop_timer(callback->timer_handle, clock);
843 void deregister(base_timer_watcher *callback, clock_type clock) noexcept
845 loop_mech.remove_timer(callback->timer_handle, clock);
847 waitqueue_node<T_Mutex> qnode;
848 get_attn_lock(qnode);
850 event_dispatch<T_Mutex, backend_traits_t> & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
851 ed.issue_delete(callback);
856 void dequeue_watcher(base_watcher *watcher) noexcept
858 loop_mech.dequeue_watcher(watcher);
861 void requeue_watcher(base_watcher *watcher) noexcept
863 loop_mech.queue_watcher(watcher);
865 // We need to signal any thread that is currently waiting on the loop mechanism, so that it wakes
866 // and processes the newly queued watcher:
869 bool attn_q_empty = attn_waitqueue.is_empty();
872 if (! attn_q_empty) {
873 loop_mech.interrupt_wait();
877 // Acquire the attention lock (when held, ensures that no thread is polling the AEN
878 // mechanism). This can be used to safely remove watches, since it is certain that
879 // notification callbacks won't be run while the attention lock is held.
880 void get_attn_lock(waitqueue_node<T_Mutex> &qnode) noexcept
882 std::unique_lock<T_Mutex> ulock(wait_lock);
883 attn_waitqueue.queue(&qnode);
884 if (! attn_waitqueue.check_head(qnode)) {
885 loop_mech.interrupt_wait();
886 while (! attn_waitqueue.check_head(qnode)) {
892 // Acquire the poll-wait lock (to be held when polling the AEN mechanism; lower priority than
893 // the attention lock). The poll-wait lock is used to prevent more than a single thread from
894 // polling the event loop mechanism at a time; if this is not done, it is basically
895 // impossible to safely deregister watches.
896 void get_pollwait_lock(waitqueue_node<T_Mutex> &qnode) noexcept
898 std::unique_lock<T_Mutex> ulock(wait_lock);
899 if (attn_waitqueue.is_empty()) {
900 // Queue is completely empty:
901 attn_waitqueue.queue(&qnode);
904 wait_waitqueue.queue(&qnode);
907 while (! attn_waitqueue.check_head(qnode)) {
912 // Release the poll-wait/attention lock.
913 void release_lock(waitqueue_node<T_Mutex> &qnode) noexcept
915 std::unique_lock<T_Mutex> ulock(wait_lock);
916 waitqueue_node<T_Mutex> * nhead = attn_waitqueue.unqueue();
917 if (nhead != nullptr) {
921 if (! wait_waitqueue.is_empty()) {
922 auto nhead = wait_waitqueue.get_head();
923 wait_waitqueue.unqueue();
924 attn_waitqueue.queue(nhead);
930 void process_signal_rearm(base_signal_watcher * bsw, rearm rearm_type) noexcept
932 // Called with lock held
933 if (rearm_type == rearm::REARM) {
934 loop_mech.rearm_signal_watch_nolock(bsw->siginfo.get_signo(), bsw);
936 else if (rearm_type == rearm::REMOVE) {
937 loop_mech.remove_signal_watch_nolock(bsw->siginfo.get_signo());
939 // Note that signal watchers cannot (currently) be disarmed
942 // Process rearm return for fd_watcher, including the primary watcher of a bidi_fd_watcher
943 rearm process_fd_rearm(base_fd_watcher * bfw, rearm rearm_type, bool is_multi_watch) noexcept
945 bool emulatedfd = static_cast<base_watcher *>(bfw)->emulatefd;
947 // Called with lock held
948 if (is_multi_watch) {
949 base_bidi_fd_watcher * bdfw = static_cast<base_bidi_fd_watcher *>(bfw);
951 if (rearm_type == rearm::REMOVE) {
952 bdfw->read_removed = 1;
954 if (backend_traits_t::has_separate_rw_fd_watches) {
955 bdfw->watch_flags &= ~IN_EVENTS;
957 loop_mech.remove_fd_watch_nolock(bdfw->watch_fd, IN_EVENTS);
959 return bdfw->write_removed ? rearm::REMOVE : rearm::NOOP;
962 if (! bdfw->write_removed) {
963 if (bdfw->watch_flags & IN_EVENTS) {
964 bdfw->watch_flags &= ~IN_EVENTS;
966 loop_mech.enable_fd_watch_nolock(bdfw->watch_fd, bdfw, bdfw->watch_flags);
972 // both removed: actually remove
974 loop_mech.remove_fd_watch_nolock(bdfw->watch_fd, 0 /* not used */);
976 return rearm::REMOVE;
980 else if (rearm_type == rearm::DISARM) {
981 bdfw->watch_flags &= ~IN_EVENTS;
984 if (! backend_traits_t::has_separate_rw_fd_watches) {
985 int watch_flags = bdfw->watch_flags;
986 // without separate r/w watches, enable_fd_watch actually sets
987 // which sides are enabled (i.e. can be used to disable):
988 loop_mech.enable_fd_watch_nolock(bdfw->watch_fd,
989 static_cast<base_watcher *>(bdfw),
990 (watch_flags & (IN_EVENTS | OUT_EVENTS)) | ONE_SHOT);
993 loop_mech.disable_fd_watch_nolock(bdfw->watch_fd, IN_EVENTS);
997 else if (rearm_type == rearm::REARM) {
998 bdfw->watch_flags |= IN_EVENTS;
1001 if (! backend_traits_t::has_separate_rw_fd_watches) {
1002 int watch_flags = bdfw->watch_flags;
1003 loop_mech.enable_fd_watch_nolock(bdfw->watch_fd,
1004 static_cast<base_watcher *>(bdfw),
1005 (watch_flags & (IN_EVENTS | OUT_EVENTS)) | ONE_SHOT);
1008 loop_mech.enable_fd_watch_nolock(bdfw->watch_fd,
1009 static_cast<base_watcher *>(bdfw),
1010 IN_EVENTS | ONE_SHOT);
1014 rearm_type = rearm::REQUEUE;
1017 else if (rearm_type == rearm::NOOP) {
1018 if (bdfw->emulatefd) {
1019 if (bdfw->watch_flags & IN_EVENTS) {
1020 rearm_type = rearm::REQUEUE;
1026 else { // Not multi-watch:
1028 if (rearm_type == rearm::REARM) {
1029 bfw->emulate_enabled = true;
1030 rearm_type = rearm::REQUEUE;
1032 else if (rearm_type == rearm::DISARM) {
1033 bfw->emulate_enabled = false;
1035 else if (rearm_type == rearm::NOOP) {
1036 if (bfw->emulate_enabled) {
1037 rearm_type = rearm::REQUEUE;
1041 else if (rearm_type == rearm::REARM) {
1042 loop_mech.enable_fd_watch_nolock(bfw->watch_fd, bfw,
1043 (bfw->watch_flags & (IN_EVENTS | OUT_EVENTS)) | ONE_SHOT);
1045 else if (rearm_type == rearm::DISARM) {
1046 loop_mech.disable_fd_watch_nolock(bfw->watch_fd, bfw->watch_flags);
1048 else if (rearm_type == rearm::REMOVE) {
1049 loop_mech.remove_fd_watch_nolock(bfw->watch_fd, bfw->watch_flags);
1055 // Process re-arm for the secondary (output) watcher in a Bi-direction Fd watcher.
1056 rearm process_secondary_rearm(base_bidi_fd_watcher * bdfw, base_watcher * outw, rearm rearm_type) noexcept
1058 bool emulatedfd = outw->emulatefd;
1060 // Called with lock held
1062 if (rearm_type == rearm::REMOVE) {
1063 bdfw->write_removed = 1;
1064 bdfw->watch_flags &= ~OUT_EVENTS;
1065 rearm_type = bdfw->read_removed ? rearm::REMOVE : rearm::NOOP;
1067 else if (rearm_type == rearm::DISARM) {
1068 bdfw->watch_flags &= ~OUT_EVENTS;
1070 else if (rearm_type == rearm::REARM) {
1071 bdfw->watch_flags |= OUT_EVENTS;
1072 rearm_type = rearm::REQUEUE;
1074 else if (rearm_type == rearm::NOOP) {
1075 if (bdfw->watch_flags & OUT_EVENTS) {
1076 rearm_type = rearm::REQUEUE;
1081 else if (rearm_type == rearm::REMOVE) {
1082 bdfw->write_removed = 1;
1084 if (backend_traits_t::has_separate_rw_fd_watches) {
1085 bdfw->watch_flags &= ~OUT_EVENTS;
1086 loop_mech.remove_fd_watch_nolock(bdfw->watch_fd, OUT_EVENTS);
1087 return bdfw->read_removed ? rearm::REMOVE : rearm::NOOP;
1090 if (! bdfw->read_removed) {
1091 if (bdfw->watch_flags & OUT_EVENTS) {
1092 bdfw->watch_flags &= ~OUT_EVENTS;
1093 loop_mech.enable_fd_watch_nolock(bdfw->watch_fd, bdfw, bdfw->watch_flags);
1098 // both removed: actually remove
1099 loop_mech.remove_fd_watch_nolock(bdfw->watch_fd, 0 /* not used */);
1100 return rearm::REMOVE;
1104 else if (rearm_type == rearm::DISARM) {
1105 bdfw->watch_flags &= ~OUT_EVENTS;
1107 if (! backend_traits_t::has_separate_rw_fd_watches) {
1108 int watch_flags = bdfw->watch_flags;
1109 loop_mech.enable_fd_watch_nolock(bdfw->watch_fd,
1110 static_cast<base_watcher *>(bdfw),
1111 (watch_flags & (IN_EVENTS | OUT_EVENTS)) | ONE_SHOT);
1114 loop_mech.disable_fd_watch_nolock(bdfw->watch_fd, OUT_EVENTS);
1117 else if (rearm_type == rearm::REARM) {
1118 bdfw->watch_flags |= OUT_EVENTS;
1120 if (! backend_traits_t::has_separate_rw_fd_watches) {
1121 int watch_flags = bdfw->watch_flags;
1122 loop_mech.enable_fd_watch_nolock(bdfw->watch_fd,
1123 static_cast<base_watcher *>(bdfw),
1124 (watch_flags & (IN_EVENTS | OUT_EVENTS)) | ONE_SHOT);
1127 loop_mech.enable_fd_watch_nolock(bdfw->watch_fd,
1128 static_cast<base_watcher *>(bdfw),
1129 OUT_EVENTS | ONE_SHOT);
1135 void process_child_watch_rearm(base_child_watcher *bcw, rearm rearm_type) noexcept
1137 if (rearm_type == rearm::REMOVE || rearm_type == rearm::DISARM) {
1138 loop_mech.unreserve_child_watch_nolock(bcw->watch_handle);
1142 void process_timer_rearm(base_timer_watcher *btw, rearm rearm_type) noexcept
1144 // Called with lock held
1145 if (rearm_type == rearm::REARM) {
1146 loop_mech.enable_timer_nolock(btw->timer_handle, true, btw->clock);
1148 else if (rearm_type == rearm::REMOVE) {
1149 loop_mech.remove_timer_nolock(btw->timer_handle, btw->clock);
1151 else if (rearm_type == rearm::DISARM) {
1152 loop_mech.enable_timer_nolock(btw->timer_handle, false, btw->clock);
1156 // Process queued events; returns true if any events were processed.
1157 // limit - maximum number of events to process before returning; -1 for
1159 bool process_events(int limit) noexcept
1161 auto & ed = (event_dispatch<T_Mutex, backend_traits_t> &) loop_mech;
1168 base_watcher * pqueue = ed.pull_event();
1169 bool active = false;
1171 while (pqueue != nullptr) {
1173 pqueue->active = true;
1176 base_bidi_fd_watcher *bbfw = nullptr;
1178 // (Above variables are initialised only to silence compiler warnings).
1180 if (pqueue->watchType == watch_type_t::SECONDARYFD) {
1181 // construct a pointer to the main watcher (using char* arithmetic):
1182 char * rp = (char *)pqueue;
1184 // Here we take the offset of a member from a non-standard-layout class, which is
1185 // specified to have undefined result by the C++ language standard, but which
1186 // in practice works fine:
1187 _Pragma ("GCC diagnostic push")
1188 _Pragma ("GCC diagnostic ignored \"-Winvalid-offsetof\"")
1189 rp -= offsetof(base_bidi_fd_watcher, out_watcher);
1190 _Pragma ("GCC diagnostic pop")
1191 bbfw = (base_bidi_fd_watcher *)rp;
1193 // issue a secondary dispatch:
1194 bbfw->dispatch_second(this);
1195 pqueue = ed.pull_event();
1199 pqueue->dispatch(this);
1202 if (limit == 0) break;
1204 pqueue = ed.pull_event();
1213 using fd_watcher = dprivate::fd_watcher<my_event_loop_t>;
1214 using bidi_fd_watcher = dprivate::bidi_fd_watcher<my_event_loop_t>;
1215 using signal_watcher = dprivate::signal_watcher<my_event_loop_t>;
1216 using child_proc_watcher = dprivate::child_proc_watcher<my_event_loop_t>;
1217 using timer = dprivate::timer<my_event_loop_t>;
1219 template <typename D> using fd_watcher_impl = dprivate::fd_watcher_impl<my_event_loop_t, D>;
1220 template <typename D> using bidi_fd_watcher_impl = dprivate::bidi_fd_watcher_impl<my_event_loop_t, D>;
1221 template <typename D> using signal_watcher_impl = dprivate::signal_watcher_impl<my_event_loop_t, D>;
1222 template <typename D> using child_proc_watcher_impl = dprivate::child_proc_watcher_impl<my_event_loop_t, D>;
1223 template <typename D> using timer_impl = dprivate::timer_impl<my_event_loop_t, D>;
1225 // Poll the event loop and process any pending events (up to a limit). If no events are pending, wait
1226 // for and process at least one event.
1227 void run(int limit = -1) noexcept
1229 // Poll the mechanism first, in case high-priority events are pending:
1230 waitqueue_node<T_Mutex> qnode;
1231 get_pollwait_lock(qnode);
1232 loop_mech.pull_events(false);
1233 release_lock(qnode);
1235 while (! process_events(limit)) {
1236 // Pull events from the AEN mechanism and insert them in our internal queue:
1237 get_pollwait_lock(qnode);
1238 loop_mech.pull_events(true);
1239 release_lock(qnode);
1243 // Poll the event loop and process any pending events (up to a limit).
1244 void poll(int limit = -1) noexcept
1246 waitqueue_node<T_Mutex> qnode;
1247 get_pollwait_lock(qnode);
1248 loop_mech.pull_events(false);
1249 release_lock(qnode);
1251 process_events(limit);
1254 // Get the current time corresponding to a specific clock.
1255 // ts - the timespec variable to receive the time
1256 // clock - specifies the clock
1257 // force_update (default = false) - if true, the time returned will be updated from
1258 // the system rather than being a previously cached result. It may be more
1259 // accurate, but note that reading from a system clock may be relatively expensive.
1260 void get_time(timespec &ts, clock_type clock, bool force_update = false) noexcept
1262 loop_mech.get_time(ts, clock, force_update);
1265 void get_time(time_val &tv, clock_type clock, bool force_update = false) noexcept
1267 loop_mech.get_time(tv, clock, force_update);
1271 event_loop(const event_loop &other) = delete;
1274 typedef event_loop<null_mutex> event_loop_n;
1275 typedef event_loop<std::mutex> event_loop_th;
1277 namespace dprivate {
1279 // Posix signal event watcher
1280 template <typename EventLoop>
1281 class signal_watcher : private dprivate::base_signal_watcher<typename EventLoop::mutex_t, typename EventLoop::loop_traits_t::sigdata_t>
1283 template <typename, typename> friend class signal_watcher_impl;
1285 using base_watcher = dprivate::base_watcher;
1286 using T_Mutex = typename EventLoop::mutex_t;
1289 using event_loop_t = EventLoop;
1290 using siginfo_p = typename signal_watcher::siginfo_p;
1292 // Register this watcher to watch the specified signal.
1293 // If an attempt is made to register with more than one event loop at
1294 // a time, behaviour is undefined. The signal should be masked before
1296 inline void add_watch(event_loop_t &eloop, int signo, int prio = DEFAULT_PRIORITY)
1298 base_watcher::init();
1299 this->priority = prio;
1300 this->siginfo.set_signo(signo);
1301 eloop.register_signal(this, signo);
1304 inline void deregister(event_loop_t &eloop) noexcept
1306 eloop.deregister(this, this->siginfo.get_signo());
1309 template <typename T>
1310 static signal_watcher<event_loop_t> *add_watch(event_loop_t &eloop, int signo, T watch_hndlr)
1312 class lambda_sig_watcher : public signal_watcher_impl<event_loop_t, lambda_sig_watcher>
1318 lambda_sig_watcher(T watch_handlr_a) : watch_hndlr(watch_handlr_a)
1323 rearm received(event_loop_t &eloop, int signo, siginfo_p siginfo)
1325 return watch_hndlr(eloop, signo, siginfo);
1328 void watch_removed() noexcept override
1334 lambda_sig_watcher * lsw = new lambda_sig_watcher(watch_hndlr);
1335 lsw->add_watch(eloop, signo);
1339 // virtual rearm received(EventLoop &eloop, int signo, siginfo_p siginfo) = 0;
1342 template <typename EventLoop, typename Derived>
1343 class signal_watcher_impl : public signal_watcher<EventLoop>
1345 void dispatch(void *loop_ptr) noexcept override
1347 EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
1348 loop.get_base_lock().unlock();
1350 auto rearm_type = static_cast<Derived *>(this)->received(loop, this->siginfo.get_signo(), this->siginfo);
1352 loop.get_base_lock().lock();
1354 if (rearm_type != rearm::REMOVED) {
1356 this->active = false;
1357 if (this->deleteme) {
1358 // We don't want a watch that is marked "deleteme" to re-arm itself.
1359 rearm_type = rearm::REMOVE;
1362 loop.process_signal_rearm(this, rearm_type);
1364 post_dispatch(loop, this, rearm_type);
1369 // Posix file descriptor event watcher
1370 template <typename EventLoop>
1371 class fd_watcher : private dprivate::base_fd_watcher<typename EventLoop::mutex_t>
1373 template <typename, typename> friend class fd_watcher_impl;
1375 using base_watcher = dprivate::base_watcher;
1376 using mutex_t = typename EventLoop::mutex_t;
1380 // Set the types of event to watch. Only supported if loop_traits_t_t::has_bidi_fd_watch
1381 // is true; otherwise has unspecified behavior.
1382 // Only safe to call from within the callback handler (fdEvent). Might not take
1383 // effect until the current callback handler returns with REARM.
1384 void set_watch_flags(int newFlags)
1386 this->watch_flags = newFlags;
1391 using event_loop_t = EventLoop;
1393 // Register a file descriptor watcher with an event loop. Flags
1394 // can be any combination of dasynq::IN_EVENTS / dasynq::OUT_EVENTS.
1395 // Exactly one of IN_EVENTS/OUT_EVENTS must be specified if the event
1396 // loop does not support bi-directional fd watchers (i.e. if
1397 // ! loop_traits_t::has_bidi_fd_watch).
1399 // Mechanisms supporting dual watchers allow for two watchers for a
1400 // single file descriptor (one watching read status and the other
1401 // write status). Others mechanisms support only a single watcher
1402 // per file descriptor. Adding a watcher beyond what is supported
1403 // causes undefined behavior.
1405 // Can fail with std::bad_alloc or std::system_error.
1406 void add_watch(event_loop_t &eloop, int fd, int flags, bool enabled = true, int prio = DEFAULT_PRIORITY)
1408 base_watcher::init();
1409 this->priority = prio;
1410 this->watch_fd = fd;
1411 this->watch_flags = flags;
1412 eloop.register_fd(this, fd, flags, enabled, true);
1415 void add_watch_noemu(event_loop_t &eloop, int fd, int flags, bool enabled = true, int prio = DEFAULT_PRIORITY)
1417 base_watcher::init();
1418 this->priority = prio;
1419 this->watch_fd = fd;
1420 this->watch_flags = flags;
1421 eloop.register_fd(this, fd, flags, enabled, false);
1424 int get_watched_fd()
1426 return this->watch_fd;
1429 // Deregister a file descriptor watcher.
1431 // If other threads may be polling the event loop, it is not safe to assume
1432 // the watcher is unregistered until the watch_removed() callback is issued
1433 // (which will not occur until the event handler returns, if it is active).
1434 // In a single threaded environment, it is safe to delete the watcher after
1435 // calling this method as long as the handler (if it is active) accesses no
1436 // internal state and returns rearm::REMOVED.
1437 void deregister(event_loop_t &eloop) noexcept
1439 eloop.deregister(this, this->watch_fd);
1442 void set_enabled(event_loop_t &eloop, bool enable) noexcept
1444 std::lock_guard<mutex_t> guard(eloop.get_base_lock());
1445 if (this->emulatefd) {
1446 this->emulate_enabled = enable;
1449 eloop.set_fd_enabled_nolock(this, this->watch_fd, this->watch_flags, enable);
1452 eloop.dequeue_watcher(this);
1456 // Add an Fd watch via a lambda. The watch is allocated dynamically and destroys
1457 // itself when removed from the event loop.
1458 template <typename T>
1459 static fd_watcher<EventLoop> *add_watch(event_loop_t &eloop, int fd, int flags, T watchHndlr)
1461 class lambda_fd_watcher : public fd_watcher_impl<event_loop_t, lambda_fd_watcher>
1467 lambda_fd_watcher(T watchHandlr_a) : watchHndlr(watchHandlr_a)
1472 rearm fd_event(event_loop_t &eloop, int fd, int flags)
1474 return watchHndlr(eloop, fd, flags);
1477 void watch_removed() noexcept override
1483 lambda_fd_watcher * lfd = new lambda_fd_watcher(watchHndlr);
1484 lfd->add_watch(eloop, fd, flags);
1488 // virtual rearm fd_event(EventLoop &eloop, int fd, int flags) = 0;
1491 template <typename EventLoop, typename Derived>
1492 class fd_watcher_impl : public fd_watcher<EventLoop>
1494 void dispatch(void *loop_ptr) noexcept override
1496 EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
1498 // In case emulating, clear enabled here; REARM or explicit set_enabled will re-enable.
1499 this->emulate_enabled = false;
1501 loop.get_base_lock().unlock();
1503 auto rearm_type = static_cast<Derived *>(this)->fd_event(loop, this->watch_fd, this->event_flags);
1505 loop.get_base_lock().lock();
1507 if (rearm_type != rearm::REMOVED) {
1508 this->event_flags = 0;
1509 this->active = false;
1510 if (this->deleteme) {
1511 // We don't want a watch that is marked "deleteme" to re-arm itself.
1512 rearm_type = rearm::REMOVE;
1515 rearm_type = loop.process_fd_rearm(this, rearm_type, false);
1517 post_dispatch(loop, this, rearm_type);
1523 // A Bi-directional file descriptor watcher with independent read- and write- channels.
1524 // This watcher type has two event notification methods which can both potentially be
1525 // active at the same time.
1526 template <typename EventLoop>
1527 class bidi_fd_watcher : private dprivate::base_bidi_fd_watcher<typename EventLoop::mutex_t>
1529 template <typename, typename> friend class bidi_fd_watcher_impl;
1531 using base_watcher = dprivate::base_watcher;
1532 using mutex_t = typename EventLoop::mutex_t;
1534 void set_watch_enabled(EventLoop &eloop, bool in, bool b)
1536 int events = in ? IN_EVENTS : OUT_EVENTS;
1539 this->watch_flags |= events;
1542 this->watch_flags &= ~events;
1545 dprivate::base_watcher * watcher = in ? this : &this->out_watcher;
1547 if (! watcher->emulatefd) {
1548 if (EventLoop::loop_traits_t::has_separate_rw_fd_watches) {
1549 eloop.set_fd_enabled_nolock(this, this->watch_fd, events | ONE_SHOT, b);
1552 eloop.set_fd_enabled_nolock(this, this->watch_fd,
1553 (this->watch_flags & IO_EVENTS) | ONE_SHOT,
1554 (this->watch_flags & IO_EVENTS) != 0);
1559 eloop.dequeue_watcher(watcher);
1565 using event_loop_t = EventLoop;
1567 void set_in_watch_enabled(event_loop_t &eloop, bool b) noexcept
1569 eloop.get_base_lock().lock();
1570 set_watch_enabled(eloop, true, b);
1571 eloop.get_base_lock().unlock();
1574 void set_out_watch_enabled(event_loop_t &eloop, bool b) noexcept
1576 eloop.get_base_lock().lock();
1577 set_watch_enabled(eloop, false, b);
1578 eloop.get_base_lock().unlock();
1581 // Set the watch flags, which enables/disables both the in-watch and the out-watch accordingly.
1583 // Concurrency: this method can only be called if
1584 // - it does not enable a watcher that might currently be active
1585 /// - unless the event loop will not be polled while the watcher is active.
1586 // (i.e. it is ok to call setWatchFlags from within the readReady/writeReady handlers if no other
1587 // thread will poll the event loop; it is always ok to *dis*able a watcher that might be active,
1588 // though the re-arm action returned by the callback may undo the effect).
1589 void set_watches(event_loop_t &eloop, int new_flags) noexcept
1591 std::lock_guard<mutex_t> guard(eloop.get_base_lock());
1592 bool use_emulation = this->emulatefd || this->out_watcher.emulatefd;
1593 if (use_emulation || EventLoop::loop_traits_t::has_separate_rw_fd_watches) {
1594 set_watch_enabled(eloop, true, (new_flags & IN_EVENTS) != 0);
1595 set_watch_enabled(eloop, false, (new_flags & OUT_EVENTS) != 0);
1598 this->watch_flags = (this->watch_flags & ~IO_EVENTS) | new_flags;
1599 eloop.set_fd_enabled_nolock((dprivate::base_watcher *) this, this->watch_fd, this->watch_flags & IO_EVENTS, true);
1603 // Register a bi-direction file descriptor watcher with an event loop. Flags
1604 // can be any combination of dasynq::IN_EVENTS / dasynq::OUT_EVENTS.
1606 // Can fail with std::bad_alloc or std::system_error.
1607 void add_watch(event_loop_t &eloop, int fd, int flags, int inprio = DEFAULT_PRIORITY, int outprio = DEFAULT_PRIORITY)
1609 base_watcher::init();
1610 this->out_watcher.base_watcher::init();
1611 this->watch_fd = fd;
1612 this->watch_flags = flags | dprivate::multi_watch;
1613 this->read_removed = false;
1614 this->write_removed = false;
1615 this->priority = inprio;
1616 this->set_priority(this->out_watcher, outprio);
1617 eloop.register_fd(this, fd, flags, true);
1620 void add_watch_noemu(event_loop_t &eloop, int fd, int flags, int inprio = DEFAULT_PRIORITY, int outprio = DEFAULT_PRIORITY)
1622 base_watcher::init();
1623 this->out_watcher.base_watcher::init();
1624 this->watch_fd = fd;
1625 this->watch_flags = flags | dprivate::multi_watch;
1626 this->read_removed = false;
1627 this->write_removed = false;
1628 this->priority = inprio;
1629 this->set_priority(this->out_watcher, outprio);
1630 eloop.register_fd(this, fd, flags, false);
1633 int get_watched_fd()
1635 return this->watch_fd;
1638 // Deregister a bi-direction file descriptor watcher.
1640 // If other threads may be polling the event loop, it is not safe to assume
1641 // the watcher is unregistered until the watch_removed() callback is issued
1642 // (which will not occur until the event handler returns, if it is active).
1643 // In a single threaded environment, it is safe to delete the watcher after
1644 // calling this method as long as the handler (if it is active) accesses no
1645 // internal state and returns rearm::REMOVED.
1646 void deregister(event_loop_t &eloop) noexcept
1648 eloop.deregister(this, this->watch_fd);
1651 template <typename T>
1652 static bidi_fd_watcher<event_loop_t> *add_watch(event_loop_t &eloop, int fd, int flags, T watch_hndlr)
1654 class lambda_bidi_watcher : public bidi_fd_watcher_impl<event_loop_t, lambda_bidi_watcher>
1660 lambda_bidi_watcher(T watch_handlr_a) : watch_hndlr(watch_handlr_a)
1665 rearm read_ready(event_loop_t &eloop, int fd)
1667 return watch_hndlr(eloop, fd, IN_EVENTS);
1670 rearm write_ready(event_loop_t &eloop, int fd)
1672 return watch_hndlr(eloop, fd, OUT_EVENTS);
1675 void watch_removed() noexcept override
1681 lambda_bidi_watcher * lfd = new lambda_bidi_watcher(watch_hndlr);
1682 lfd->add_watch(eloop, fd, flags);
1686 // virtual rearm read_ready(EventLoop &eloop, int fd) noexcept = 0;
1687 // virtual rearm write_ready(EventLoop &eloop, int fd) noexcept = 0;
1690 template <typename EventLoop, typename Derived>
1691 class bidi_fd_watcher_impl : public bidi_fd_watcher<EventLoop>
1693 void dispatch(void *loop_ptr) noexcept override
1695 EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
1696 this->emulate_enabled = false;
1697 loop.get_base_lock().unlock();
1699 auto rearm_type = static_cast<Derived *>(this)->read_ready(loop, this->watch_fd);
1701 loop.get_base_lock().lock();
1703 if (rearm_type != rearm::REMOVED) {
1704 this->event_flags &= ~IN_EVENTS;
1705 this->active = false;
1706 if (this->deleteme) {
1707 // We don't want a watch that is marked "deleteme" to re-arm itself.
1708 rearm_type = rearm::REMOVE;
1711 rearm_type = loop.process_fd_rearm(this, rearm_type, true);
1713 post_dispatch(loop, this, rearm_type);
1717 void dispatch_second(void *loop_ptr) noexcept override
1719 auto &outwatcher = bidi_fd_watcher<EventLoop>::out_watcher;
1721 EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
1722 loop.get_base_lock().unlock();
1724 auto rearm_type = static_cast<Derived *>(this)->write_ready(loop, this->watch_fd);
1726 loop.get_base_lock().lock();
1728 if (rearm_type != rearm::REMOVED) {
1729 this->event_flags &= ~OUT_EVENTS;
1730 outwatcher.active = false;
1731 if (outwatcher.deleteme) {
1732 // We don't want a watch that is marked "deleteme" to re-arm itself.
1733 rearm_type = rearm::REMOVE;
1736 rearm_type = loop.process_secondary_rearm(this, &outwatcher, rearm_type);
1738 if (rearm_type == rearm::REQUEUE) {
1739 post_dispatch(loop, &outwatcher, rearm_type);
1742 post_dispatch(loop, this, rearm_type);
1748 // Child process event watcher
1749 template <typename EventLoop>
1750 class child_proc_watcher : private dprivate::base_child_watcher<typename EventLoop::mutex_t>
1752 template <typename, typename> friend class child_proc_watcher_impl;
1754 using base_watcher = dprivate::base_watcher;
1755 using mutex_t = typename EventLoop::mutex_t;
1759 using event_loop_t = EventLoop;
1761 // send a signal to this process, if it is still running, in a race-free manner.
1762 // return is as for POSIX kill(); return is -1 with errno=ESRCH if process has
1763 // already terminated.
1764 int send_signal(event_loop_t &loop, int signo) noexcept
1766 auto reaper_mutex = loop.get_reaper_mutex();
1767 std::lock_guard<decltype(reaper_mutex)> guard(reaper_mutex);
1769 if (this->child_termd) {
1774 return kill(this->watch_pid, signo);
1777 // Reserve resources for a child watcher with the given event loop.
1778 // Reservation can fail with std::bad_alloc. Some backends do not support
1779 // reservation (it will always fail) - check loop_traits_t::supports_childwatch_reservation.
1780 void reserve_watch(event_loop_t &eloop)
1782 eloop.reserve_child_watch(this);
1785 void unreserve(event_loop_t &eloop)
1787 eloop.unreserve(this);
1790 // Register a watcher for the given child process with an event loop.
1791 // Registration can fail with std::bad_alloc.
1792 // Note that in multi-threaded programs, use of this function may be prone to a
1793 // race condition such that the child terminates before the watcher is registered.
1794 void add_watch(event_loop_t &eloop, pid_t child, int prio = DEFAULT_PRIORITY)
1796 base_watcher::init();
1797 this->watch_pid = child;
1798 this->priority = prio;
1799 eloop.register_child(this, child);
1802 // Register a watcher for the given child process with an event loop,
1803 // after having reserved resources previously (using reserveWith).
1804 // Registration cannot fail.
1805 // Note that in multi-threaded programs, use of this function may be prone to a
1806 // race condition such that the child terminates before the watcher is registered;
1807 // use the "fork" member function to avoid this.
1808 void add_reserved(event_loop_t &eloop, pid_t child, int prio = DEFAULT_PRIORITY) noexcept
1810 base_watcher::init();
1811 this->watch_pid = child;
1812 this->priority = prio;
1813 eloop.register_reserved_child(this, child);
1816 void deregister(event_loop_t &eloop, pid_t child) noexcept
1818 eloop.deregister(this, child);
1821 // Stop watching the currently watched child, but retain watch reservation.
1822 void stop_watch(event_loop_t &eloop) noexcept
1824 eloop.stop_watch(this);
1827 // Fork and watch the child with this watcher on the given event loop.
1828 // If resource limitations prevent the child process from being watched, it is
1829 // terminated immediately (or if the implementation allows, never started),
1830 // and a suitable std::system_error or std::bad_alloc exception is thrown.
1832 // - the child pid in the parent
1834 pid_t fork(event_loop_t &eloop, bool from_reserved = false, int prio = DEFAULT_PRIORITY)
1836 base_watcher::init();
1837 this->priority = prio;
1839 if (EventLoop::loop_traits_t::supports_childwatch_reservation) {
1840 // Reserve a watch, fork, then claim reservation
1841 if (! from_reserved) {
1842 reserve_watch(eloop);
1845 auto &lock = eloop.get_base_lock();
1848 pid_t child = ::fork();
1853 throw std::system_error(errno, std::system_category());
1858 lock.unlock(); // may not really be necessary
1862 // Register this watcher.
1863 this->watch_pid = child;
1864 eloop.register_reserved_child_nolock(this, child);
1870 if (pipe2(pipefds, O_CLOEXEC) == -1) {
1871 throw std::system_error(errno, std::system_category());
1874 std::lock_guard<mutex_t> guard(eloop.get_base_lock());
1876 pid_t child = ::fork();
1878 throw std::system_error(errno, std::system_category());
1884 // Wait for message from parent before continuing:
1886 int r = read(pipefds[0], &rr, sizeof(rr));
1887 while (r == -1 && errno == EINTR) {
1888 read(pipefds[0], &rr, sizeof(rr));
1891 if (r == -1) _exit(0);
1897 close(pipefds[0]); // close read end
1899 // Register this watcher.
1901 this->watch_pid = child;
1902 eloop.register_child(this, child);
1904 // Continue in child (it doesn't matter what is written):
1905 write(pipefds[1], &pipefds, sizeof(int));
1917 // virtual rearm child_status(EventLoop &eloop, pid_t child, int status) = 0;
1920 template <typename EventLoop, typename Derived>
1921 class child_proc_watcher_impl : public child_proc_watcher<EventLoop>
1923 void dispatch(void *loop_ptr) noexcept override
1925 EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
1926 loop.get_base_lock().unlock();
1928 auto rearm_type = static_cast<Derived *>(this)->status_change(loop, this->watch_pid, this->child_status);
1930 loop.get_base_lock().lock();
1932 if (rearm_type != rearm::REMOVED) {
1934 this->active = false;
1935 if (this->deleteme) {
1936 // We don't want a watch that is marked "deleteme" to re-arm itself.
1937 rearm_type = rearm::REMOVE;
1940 loop.process_child_watch_rearm(this, rearm_type);
1942 // rearm_type = loop.process??;
1943 post_dispatch(loop, this, rearm_type);
1948 template <typename EventLoop>
1949 class timer : private base_timer_watcher<typename EventLoop::mutex_t>
1951 template <typename, typename> friend class timer_impl;
1952 using base_t = base_timer_watcher<typename EventLoop::mutex_t>;
1953 using mutex_t = typename EventLoop::mutex_t;
1956 using event_loop_t = EventLoop;
1958 void add_timer(event_loop_t &eloop, clock_type clock = clock_type::MONOTONIC, int prio = DEFAULT_PRIORITY)
1960 base_watcher::init();
1961 this->priority = prio;
1962 this->clock = clock;
1963 this->intervals = 0;
1964 eloop.register_timer(this, clock);
1967 void arm_timer(event_loop_t &eloop, const timespec &timeout) noexcept
1969 eloop.set_timer(this, timeout, base_t::clock);
1972 void arm_timer(event_loop_t &eloop, const timespec &timeout, const timespec &interval) noexcept
1974 eloop.set_timer(this, timeout, interval, base_t::clock);
1977 // Arm timer, relative to now:
1978 void arm_timer_rel(event_loop_t &eloop, const timespec &timeout) noexcept
1980 eloop.set_timer_rel(this, timeout, base_t::clock);
1983 void arm_timer_rel(event_loop_t &eloop, const timespec &timeout,
1984 const timespec &interval) noexcept
1986 eloop.set_timer_rel(this, timeout, interval, base_t::clock);
1989 void stop_timer(event_loop_t &eloop) noexcept
1991 eloop.stop_timer(this, base_t::clock);
1994 void set_enabled(event_loop_t &eloop, clock_type clock, bool enabled) noexcept
1996 std::lock_guard<mutex_t> guard(eloop.get_base_lock());
1997 eloop.set_timer_enabled_nolock(this, clock, enabled);
1999 eloop.dequeue_watcher(this);
2003 void deregister(event_loop_t &eloop) noexcept
2005 eloop.deregister(this, this->clock);
2008 template <typename T>
2009 static timer<EventLoop> *add_timer(EventLoop &eloop, clock_type clock, bool relative,
2010 struct timespec &timeout, struct timespec &interval, T watch_hndlr)
2012 class lambda_timer : public timer_impl<event_loop_t, lambda_timer>
2018 lambda_timer(T watch_handlr_a) : watch_hndlr(watch_handlr_a)
2023 rearm timer_expiry(event_loop_t &eloop, int intervals)
2025 return watch_hndlr(eloop, intervals);
2028 void watch_removed() noexcept override
2034 lambda_timer * lt = new lambda_timer(watch_hndlr);
2035 lt->add_timer(eloop, clock);
2037 lt->arm_timer_rel(eloop, timeout, interval);
2040 lt->arm_timer(eloop, timeout, interval);
2045 // Timer expired, and the given number of intervals have elapsed before
2046 // expiry event was queued. Normally intervals == 1 to indicate no
2048 // virtual rearm timer_expiry(event_loop_t &eloop, int intervals) = 0;
2051 template <typename EventLoop, typename Derived>
2052 class timer_impl : public timer<EventLoop>
2054 void dispatch(void *loop_ptr) noexcept override
2056 EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
2057 loop.get_base_lock().unlock();
2059 auto intervals_report = this->intervals;
2060 this->intervals = 0;
2061 auto rearm_type = static_cast<Derived *>(this)->timer_expiry(loop, intervals_report);
2063 loop.get_base_lock().lock();
2065 if (rearm_type != rearm::REMOVED) {
2067 this->active = false;
2068 if (this->deleteme) {
2069 // We don't want a watch that is marked "deleteme" to re-arm itself.
2070 rearm_type = rearm::REMOVE;
2073 loop.process_timer_rearm(this, rearm_type);
2075 post_dispatch(loop, this, rearm_type);
2080 } // namespace dasynq::dprivate
2081 } // namespace dasynq