• 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 
16 #ifndef UTILS_EVENT_REACTOR_H
17 #define UTILS_EVENT_REACTOR_H
18 
19 #include <sys/types.h>
20 #include <cstdint>
21 #include <memory>
22 #include <mutex>
23 #include <list>
24 
25 namespace OHOS {
26 namespace Utils {
27 
28 class EventDemultiplexer;
29 class EventHandler;
30 class TimerEventHandler;
31 
32 class EventReactor {
33 public:
34     using TimerCallback = std::function<void(int timerFd)>;
35     static const uint32_t NONE_EVENT  = 0x0000;
36     static const uint32_t READ_EVENT  = 0x0001;
37     static const uint32_t WRITE_EVENT = 0x0002;
38     static const uint32_t CLOSE_EVENT = 0x0004;
39     static const uint32_t ERROR_EVENT = 0x0008;
40 
41     EventReactor();
42     EventReactor(const EventReactor&) = delete;
43     EventReactor& operator=(const EventReactor&) = delete;
44     EventReactor(const EventReactor&&) = delete;
45     EventReactor& operator=(const EventReactor&&) = delete;
46     virtual ~EventReactor();
47 
48     uint32_t StartUp();
49     void CleanUp();
50 
51     void RunLoop(int timeout) const;
52     void StopLoop();
IsStopped()53     bool IsStopped() const { return stopped_; }
54 
55     void UpdateEventHandler(EventHandler* handler);
56     void RemoveEventHandler(EventHandler* handler);
57 
58     uint32_t ScheduleTimer(const TimerCallback& cb, uint32_t interval /* ms */, int& timerFd, bool once);
59     void CancelTimer(int timerFd);
60 
61 private:
62     volatile bool stopped_;
63     std::unique_ptr<EventDemultiplexer> demultiplexer_;
64     std::recursive_mutex mutex_;
65     std::list<std::shared_ptr<TimerEventHandler>> timerEventHandlers_;
66 };
67 
68 } // namespace Utils
69 } // namespace OHOS
70 #endif
71