• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef EPOLL_EVENT_POLLER_H
16 #define EPOLL_EVENT_POLLER_H
17 
18 #include <atomic>
19 #include <functional>
20 #include <memory>
21 #include <mutex>
22 #include <string>
23 #include <thread>
24 #include <unordered_map>
25 #include <vector>
26 #include "nocopyable.h"
27 
28 class EpollEventPoller {
29 public:
30     explicit EpollEventPoller(int timeOut);
31     ~EpollEventPoller();
32 
33     using OnReadableCallback = std::function<void(void)>;
34     using OnWritableCallback = std::function<void(void)>;
35 
36     bool AddFileDescriptor(int fd, const OnReadableCallback& onReadable, const OnWritableCallback& onWritable = {});
37 
38     bool RemoveFileDescriptor(int fd);
39 
40     bool Init();
41     bool Start();
42     bool Stop();
43     bool Finalize();
44 
45 private:
46     enum State {
47         INITIAL,
48         INITIED,
49         STARTED,
50     };
51     static constexpr int INVALID_FD = -1;
52     struct EventContext {
53         int fd = INVALID_FD;
54         OnReadableCallback onReadable;
55         OnWritableCallback onWritable;
56     };
57     using EventContextPtr = std::shared_ptr<EventContext>;
58 
59     void Run();
60     bool UpdateEvent(int op, const EventContextPtr& ctx);
61     void HandleEvent(uint32_t events, const EventContext& ctx);
62 
63     bool AddContextLocked(const EventContextPtr& ctx);
64     bool RemoveContextLocked(const EventContextPtr& ctx);
65 
66     void OnNotify();
67     bool Notify(uint64_t value = 1);
68 
69 private:
70     std::mutex mutex_;
71     std::mutex vecMutex_;
72     std::thread pollThread_;
73     int timeOut_ = 0;
74     int epollFd_ = INVALID_FD;
75     int eventFd_ = INVALID_FD;
76     std::atomic<int> state_ = INITIAL;
77     std::atomic<bool> running_ = false;
78     std::vector<int> fileDescriptors_;
79     std::unordered_map<int, EventContextPtr> context_;
80 
81     DISALLOW_COPY_AND_MOVE(EpollEventPoller);
82 };
83 #endif // EPOLL_EVENT_POLLER_H
84