hmbdc
simplify-high-performance-messaging-programming
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 <unistd.h>
8 
9 namespace hmbdc { namespace app { namespace utils {
10 
11 struct EpollFd;
12 struct EpollTask
13 : pattern::GuardedSingleton<EpollTask> {
14  void add(uint32_t events, EpollFd&);
15  bool del(EpollFd&);
16  void poll();
17 
18 private:
20  EpollTask(size_t maxFdCount = HMBDC_EPOLL_FD_MAX);
21 
22  ~EpollTask();
23 
24  bool stopped_;
25  int epollFd_;
26  // std::thread pollThread_;
27 };
28 
29 extern std::unique_ptr<hmbdc::pattern::SingletonGuardian<hmbdc::app::utils::EpollTask>> gEpollTaskGuard;
30 
31 struct EpollFd {
32  EpollFd(EpollFd const&) = delete;
33  EpollFd& operator = (EpollFd const&) = delete;
34  EpollFd()
35  : fd(-1)
36  , fdReady_(false)
37  , fdReadyLocal_(false)
38  {}
39 
40  virtual
41  ~EpollFd() {
42  if (fd > 0) {
43  utils::EpollTask::instance().del(*this);
44  close(fd);
45  }
46  }
47 
48  bool isFdReady() {
49  if (hmbdc_likely(fdReadyLocal_)) {
50  return true;
51  } else {
52  // return fdReadyLocal_ = __sync_val_compare_and_swap(&fdReady_, true, false);
53  return fdReadyLocal_ = __atomic_exchange_n(&fdReady_, false, __ATOMIC_RELAXED);
54  }
55  }
56 
57  bool checkErr() {
58  fdReadyLocal_ = false;
59  if (errno != EAGAIN) {
60  if (!utils::EpollTask::instance().del(*this)) {
61  } else {
62  close(fd);
63  fd = -1;
64  }
65  return false;
66  }
67  return true;
68  }
69 
70  int fd;
71 
72 private:
73  friend struct EpollTask;
74  bool fdReady_;
75  bool fdReadyLocal_;
76 };
77 }}}
78 
base for the Singleton that works with SingletonGuardian
Definition: GuardedSingleton.hpp:35
RAII representing the lifespan of the underlying Singleton which also ganrantees the singularity of u...
Definition: GuardedSingleton.hpp:20
Definition: EpollTask.hpp:12
Definition: EpollTask.hpp:31
Definition: Base.hpp:12