UniSet  2.6.0
CommonEventLoop.h
1 // -------------------------------------------------------------------------
2 #ifndef CommonEventLoop_H_
3 #define CommonEventLoop_H_
4 // -------------------------------------------------------------------------
5 #include <ev++.h>
6 #include <atomic>
7 #include <thread>
8 #include <mutex>
9 #include <condition_variable>
10 #include <vector>
11 // -------------------------------------------------------------------------
12 namespace uniset
13 {
14 
15 
16  class EvWatcher
17  {
18  public:
19  EvWatcher() {}
20  virtual ~EvWatcher() {}
21 
22  // подготовка перед запуском loop:
23  // запуск своих ev::xxx.start()
24  virtual void evprepare( const ev::loop_ref& ) {}
25 
26  // действия при завершении:
27  // вызов своих ev::xxx.stop()
28  virtual void evfinish( const ev::loop_ref& ) {}
29 
30  virtual std::string wname() const noexcept
31  {
32  return "";
33  }
34  };
35  // -------------------------------------------------------------------------
53  {
54  public:
55 
56  CommonEventLoop() noexcept;
57  ~CommonEventLoop();
58 
59  bool evIsActive() const noexcept;
60 
68  bool evrun( EvWatcher* w, bool thread = true, size_t waitPrepareTimeout_msec = 8000);
69 
71  bool evstop( EvWatcher* w );
72 
73  inline const ev::loop_ref evloop() noexcept
74  {
75  return loop;
76  }
77 
78  // количество зарегистрированных wather-ов
79  size_t size() const;
80 
81  protected:
82 
83  private:
84 
85  void onStop( ev::async& w, int revents ) noexcept;
86  void onPrepare( ev::async& w, int revents ) noexcept;
87  void defaultLoop() noexcept;
88 
89  std::atomic_bool cancelled = { false };
90  std::atomic_bool isrunning = { false };
91 
92  ev::dynamic_loop loop;
93  ev::async evterm;
94  std::shared_ptr<std::thread> thr;
95  std::mutex thr_mutex;
96 
97  std::mutex term_mutex;
98  std::condition_variable term_event;
99  std::atomic_bool term_notify = { false };
100 
101  std::mutex wlist_mutex;
102  std::vector<EvWatcher*> wlist;
103 
104  // готовящийся Watcher..он может быть только один в единицу времени
105  // это гарантирует prep_mutex
106  EvWatcher* wprep = { nullptr };
107  ev::async evprep;
108  std::condition_variable prep_event;
109  std::mutex prep_mutex;
110  std::atomic_bool prep_notify = { false };
111  };
112  // -------------------------------------------------------------------------
113 } // end of uniset namespace
114 // -------------------------------------------------------------------------
115 #endif // CommonEventLoop_H_
116 // -------------------------------------------------------------------------
The CommonEventLoop class Реализация механизма "один eventloop, много подписчиков" (libev)...
Definition: CommonEventLoop.h:52
Definition: CallbackTimer.h:29
Definition: CommonEventLoop.h:16
bool evrun(EvWatcher *w, bool thread=true, size_t waitPrepareTimeout_msec=8000)
Definition: CommonEventLoop.cc:35
bool evstop(EvWatcher *w)
Definition: CommonEventLoop.cc:126