hmbdc
simplify-high-performance-messaging-programming
 All Classes Namespaces Functions Variables Friends Pages
EpollTask.hpp
1 #include "hmbdc/Copyright.hpp"
2 #pragma once
3 #include "hmbdc/pattern/GuardedSingleton.hpp"
4 #include "hmbdc/Config.hpp"
5 #include "hmbdc/Compile.hpp"
6 #include <memory>
7 #include <mutex>
8 #include <unistd.h>
9 
10 #ifdef HMBDC_NO_EPOLL
11 #include <poll.h>
12 #else
13 #include <sys/epoll.h>
14 #endif
15 
16 namespace hmbdc { namespace app { namespace utils {
17 
18 struct EpollFd;
19 #ifndef HMBDC_NO_EPOLL
20 struct EpollTask
21 : pattern::GuardedSingleton<EpollTask> {
22  enum {
23  EPOLLIN = ::EPOLLIN,
24  EPOLLOUT = ::EPOLLOUT,
25  EPOLLET = ::EPOLLET
26  };
27  void add(uint32_t events, EpollFd&);
28  bool del(EpollFd&);
29  void poll();
30 
31 private:
33  EpollTask(size_t maxFdCount = HMBDC_EPOLL_FD_MAX);
34 
35  ~EpollTask();
36 
37  bool stopped_;
38  int epollFd_;
39  // std::thread pollThread_;
40 };
41 #else
42 struct EpollTask
43 : pattern::GuardedSingleton<EpollTask> {
44  enum {
45  EPOLLIN = POLLIN,
46  EPOLLOUT = POLLOUT,
47  EPOLLET = 0
48  };
49 
50  void add(uint32_t events, EpollFd&);
51  bool del(EpollFd&);
52  void poll();
53 
54 private:
56  EpollTask(size_t maxFdCount = HMBDC_EPOLL_FD_MAX);
57 
58  ~EpollTask();
59 
60  bool stopped_;
61  size_t maxFdCount_;
62  ::pollfd* pollFds_;
63  bool** sentinels_;
64  std::mutex lock_;
65 };
66 #endif
67 
68 extern std::unique_ptr<hmbdc::pattern::SingletonGuardian<hmbdc::app::utils::EpollTask>> gEpollTaskGuard;
69 
70 struct EpollFd {
71  EpollFd(EpollFd const&) = delete;
72  EpollFd& operator = (EpollFd const&) = delete;
73  EpollFd()
74  : fd(-1)
75  , fdReady_(false)
76  , fdReadyLocal_(false)
77  {}
78 
79  virtual
80  ~EpollFd() {
81  if (fd > 0) {
82  utils::EpollTask::instance().del(*this);
83  close(fd);
84  }
85  }
86 
87  bool isFdReady() {
88  if (hmbdc_likely(fdReadyLocal_)) {
89  return true;
90  } else {
91  // return fdReadyLocal_ = __sync_val_compare_and_swap(&fdReady_, true, false);
92  return fdReadyLocal_ = __atomic_exchange_n(&fdReady_, false, __ATOMIC_RELAXED);
93  }
94  }
95 
96  bool checkErr() {
97  fdReadyLocal_ = false;
98  if (errno != EAGAIN) {
99  if (!utils::EpollTask::instance().del(*this)) {
100  } else {
101  close(fd);
102  fd = -1;
103  }
104  return false;
105  }
106  return true;
107  }
108 
109  int fd;
110 
111 private:
112  friend struct EpollTask;
113  bool fdReady_;
114  bool fdReadyLocal_;
115 };
116 }}}
117 
base for the Singleton that works with SingletonGuardian
Definition: GuardedSingleton.hpp:53
RAII representing the lifespan of the underlying Singleton which also ganrantees the singularity of u...
Definition: GuardedSingleton.hpp:20
Definition: EpollTask.hpp:20
Definition: EpollTask.hpp:70