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 SetUp(); 49 void CleanUp(); 50 51 void RunLoop(int timeout) const; 52 void SwitchOn(); 53 void SwitchOff(); 54 IsLoopReady()55 bool IsLoopReady() const 56 { 57 return loopReady_; 58 } 59 IsSwitchedOn()60 bool IsSwitchedOn() const 61 { 62 return switch_; 63 } 64 65 void UpdateEventHandler(EventHandler* handler); 66 67 uint32_t ScheduleTimer(const TimerCallback& cb, uint32_t interval /* ms */, int& timerFd, bool once); 68 void CancelTimer(int timerFd); 69 70 private: 71 mutable volatile bool loopReady_; // refers to whether reactor is ready to call RunLoop(). 72 volatile bool switch_; // a switch to enable while-loop in RunLoop(). true: start, false: stop. 73 std::unique_ptr<EventDemultiplexer> demultiplexer_; 74 std::recursive_mutex mutex_; 75 std::list<std::shared_ptr<TimerEventHandler>> timerEventHandlers_; 76 }; 77 78 } // namespace Utils 79 } // namespace OHOS 80 #endif 81