libfilezilla
event_loop.hpp
Go to the documentation of this file.
1 #ifndef LIBFILEZILLA_EVENT_LOOP_HEADER
2 #define LIBFILEZILLA_EVENT_LOOP_HEADER
3 
4 #include "apply.hpp"
5 #include "event.hpp"
6 #include "mutex.hpp"
7 #include "time.hpp"
8 #include "thread.hpp"
9 
10 #include <deque>
11 #include <functional>
12 #include <vector>
13 
18 namespace fz {
19 
20 class event_handler;
21 
30 class FZ_PUBLIC_SYMBOL event_loop final : private thread
31 {
32 public:
33  typedef std::deque<std::pair<event_handler*, event_base*>> Events;
34 
36  event_loop();
37 
39  virtual ~event_loop();
40 
41  event_loop(event_loop const&) = delete;
42  event_loop& operator=(event_loop const&) = delete;
43 
55  void filter_events(std::function<bool (Events::value_type&)> const& filter);
56 
61  void stop();
62 
63 private:
64  friend class event_handler;
65 
66  void FZ_PRIVATE_SYMBOL remove_handler(event_handler* handler);
67 
68  timer_id FZ_PRIVATE_SYMBOL add_timer(event_handler* handler, duration const& interval, bool one_shot);
69  void FZ_PRIVATE_SYMBOL stop_timer(timer_id id);
70 
71  void send_event(event_handler* handler, event_base* evt);
72 
73  // Process the next (if any) event. Returns true if an event has been processed
74  bool FZ_PRIVATE_SYMBOL process_event(scoped_lock & l);
75 
76  // Process timers. Returns true if a timer has been triggered
77  bool FZ_PRIVATE_SYMBOL process_timers(scoped_lock & l, monotonic_clock& now);
78 
79  virtual void FZ_PRIVATE_SYMBOL entry();
80 
81  struct timer_data final
82  {
83  event_handler* handler_{};
84  timer_id id_{};
85  monotonic_clock deadline_;
86  duration interval_{};
87  };
88 
89  typedef std::vector<timer_data> Timers;
90 
91  Events pending_events_;
92  Timers timers_;
93 
94  mutex sync_;
95  condition cond_;
96 
97  bool quit_{};
98 
99  event_handler * active_handler_{};
100 
101 
102  monotonic_clock deadline_;
103 
104  timer_id next_timer_id_{};
105 };
106 
107 }
108 #endif
Spawns and represents a new thread of execution.
Definition: thread.hpp:25
Thread synchronization primitives: mutex, scoped_lock and condition.
A simple scoped lock.
Definition: mutex.hpp:61
Simple handler for asynchronous event processing.
Definition: event_handler.hpp:54
Waitable condition variable.
Definition: mutex.hpp:132
Assorted classes dealing with time.
A threaded event loop that supports sending events and timers.
Definition: event_loop.hpp:30
Declares thread.
A monotonic clock (aka steady clock) is independent from walltime.
Definition: time.hpp:353
The namespace used by libfilezilla.
Definition: apply.hpp:16
The duration class represents a time interval in milliseconds.
Definition: time.hpp:271
Declares event_base and simple_event<>
Template helper to call a function with its arguments extracted from a tuple.
Lean replacement for std::(recursive_)mutex.
Definition: mutex.hpp:27
Common base class for all events.
Definition: event.hpp:21