File: epoll_event_dispatcher.h

package info (click to toggle)
android-platform-frameworks-native 1%3A10.0.0%2Br36-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 25,828 kB
  • sloc: cpp: 252,025; xml: 52,812; ansic: 26,775; java: 5,107; python: 1,887; sh: 266; asm: 105; makefile: 23
file content (63 lines) | stat: -rw-r--r-- 1,801 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#ifndef ANDROID_DVR_SERVICES_DISPLAYD_EPOLL_EVENT_DISPATCHER_H_
#define ANDROID_DVR_SERVICES_DISPLAYD_EPOLL_EVENT_DISPATCHER_H_

#include <sys/epoll.h>

#include <atomic>
#include <functional>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <vector>

#include <pdx/file_handle.h>
#include <pdx/status.h>

namespace android {
namespace dvr {

class EpollEventDispatcher {
 public:
  // Function type for event handlers. The handler receives a bitmask of the
  // epoll events that occurred on the file descriptor associated with the
  // handler.
  using Handler = std::function<void(int)>;

  EpollEventDispatcher();
  ~EpollEventDispatcher();

  // |handler| is called on the internal dispatch thread when |fd| is signaled
  // by events in |event_mask|.
  pdx::Status<void> AddEventHandler(int fd, int event_mask, Handler handler);
  pdx::Status<void> RemoveEventHandler(int fd);

  void Stop();

 private:
  void EventThread();

  std::thread thread_;
  std::atomic<bool> exit_thread_{false};

  // Protects handlers_ and removed_handlers_ and serializes operations on
  // epoll_fd_ and event_fd_.
  std::mutex lock_;

  // Maintains a map of fds to event handlers. This is primarily to keep any
  // references alive that may be bound in the std::function instances. It is
  // not used at dispatch time to avoid performance problems with different
  // versions of std::unordered_map.
  std::unordered_map<int, Handler> handlers_;

  // List of fds to be removed from the map. The actual removal is performed
  // by the event dispatch thread to avoid races.
  std::vector<int> removed_handlers_;

  pdx::LocalHandle epoll_fd_;
  pdx::LocalHandle event_fd_;
};

}  // namespace dvr
}  // namespace android

#endif  // ANDROID_DVR_SERVICES_DISPLAYD_EPOLL_EVENT_DISPATCHER_H_