epoll_event_dispatcher.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #ifndef ANDROID_DVR_SERVICES_DISPLAYD_EPOLL_EVENT_DISPATCHER_H_
  2. #define ANDROID_DVR_SERVICES_DISPLAYD_EPOLL_EVENT_DISPATCHER_H_
  3. #include <sys/epoll.h>
  4. #include <atomic>
  5. #include <functional>
  6. #include <mutex>
  7. #include <thread>
  8. #include <unordered_map>
  9. #include <vector>
  10. #include <pdx/file_handle.h>
  11. #include <pdx/status.h>
  12. namespace android {
  13. namespace dvr {
  14. class EpollEventDispatcher {
  15. public:
  16. // Function type for event handlers. The handler receives a bitmask of the
  17. // epoll events that occurred on the file descriptor associated with the
  18. // handler.
  19. using Handler = std::function<void(int)>;
  20. EpollEventDispatcher();
  21. ~EpollEventDispatcher();
  22. // |handler| is called on the internal dispatch thread when |fd| is signaled
  23. // by events in |event_mask|.
  24. pdx::Status<void> AddEventHandler(int fd, int event_mask, Handler handler);
  25. pdx::Status<void> RemoveEventHandler(int fd);
  26. void Stop();
  27. private:
  28. void EventThread();
  29. std::thread thread_;
  30. std::atomic<bool> exit_thread_{false};
  31. // Protects handlers_ and removed_handlers_ and serializes operations on
  32. // epoll_fd_ and event_fd_.
  33. std::mutex lock_;
  34. // Maintains a map of fds to event handlers. This is primarily to keep any
  35. // references alive that may be bound in the std::function instances. It is
  36. // not used at dispatch time to avoid performance problems with different
  37. // versions of std::unordered_map.
  38. std::unordered_map<int, Handler> handlers_;
  39. // List of fds to be removed from the map. The actual removal is performed
  40. // by the event dispatch thread to avoid races.
  41. std::vector<int> removed_handlers_;
  42. pdx::LocalHandle epoll_fd_;
  43. pdx::LocalHandle event_fd_;
  44. };
  45. } // namespace dvr
  46. } // namespace android
  47. #endif // ANDROID_DVR_SERVICES_DISPLAYD_EPOLL_EVENT_DISPATCHER_H_