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 #define EPOLL_CRITICAL_ERROR (-10) 29 30 class EventDemultiplexer; 31 class EventHandler; 32 class TimerEventHandler; 33 34 class EventReactor { 35 public: 36 using TimerCallback = std::function<void(int timerFd)>; 37 static const uint32_t NONE_EVENT = 0x0000; 38 static const uint32_t READ_EVENT = 0x0001; 39 static const uint32_t WRITE_EVENT = 0x0002; 40 static const uint32_t CLOSE_EVENT = 0x0004; 41 static const uint32_t ERROR_EVENT = 0x0008; 42 43 EventReactor(); 44 EventReactor(const EventReactor&) = delete; 45 EventReactor& operator=(const EventReactor&) = delete; 46 EventReactor(const EventReactor&&) = delete; 47 EventReactor& operator=(const EventReactor&&) = delete; 48 virtual ~EventReactor(); 49 50 uint32_t SetUp(); 51 void CleanUp(); 52 53 void RunLoop(int timeout) const; 54 void SwitchOn(); 55 void SwitchOff(); 56 IsLoopReady()57 bool IsLoopReady() const 58 { 59 return loopReady_; 60 } 61 IsSwitchedOn()62 bool IsSwitchedOn() const 63 { 64 return switch_; 65 } 66 67 void UpdateEventHandler(EventHandler* handler); 68 69 uint32_t ScheduleTimer(const TimerCallback& cb, uint32_t interval /* ms */, int& timerFd, bool once); 70 void CancelTimer(int timerFd); 71 72 private: 73 mutable volatile bool loopReady_; // refers to whether reactor is ready to call RunLoop(). 74 volatile bool switch_; // a switch to enable while-loop in RunLoop(). true: start, false: stop. 75 std::unique_ptr<EventDemultiplexer> demultiplexer_; 76 std::recursive_mutex mutex_; 77 std::list<std::shared_ptr<TimerEventHandler>> timerEventHandlers_; 78 }; 79 80 } // namespace Utils 81 } // namespace OHOS 82 #endif 83