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 EVENT_LOOP_IMPL_H 17 #define EVENT_LOOP_IMPL_H 18 19 #include <list> 20 #include <set> 21 #include <thread> 22 #include "platform_specific.h" 23 #include "ievent_loop.h" 24 #include "ievent.h" 25 26 #if defined EVLOOP_TIMER_ONLY 27 #define EVENT_LOOP_USE_SELECT 28 #else 29 #define EVENT_LOOP_USE_EPOLL 30 #endif 31 32 namespace DistributedDB { 33 class EventImpl; 34 class EventRequest; 35 36 class EventLoopImpl : public IEventLoop { 37 public: 38 EventLoopImpl(); 39 ~EventLoopImpl() override; 40 DISABLE_COPY_ASSIGN_MOVE(EventLoopImpl); 41 42 int Add(IEvent *event) override; 43 int Remove(IEvent *event) override; 44 int Run() override; 45 int Stop() override; 46 int Modify(EventImpl *event, bool isAdd, EventsMask events); 47 int Modify(EventImpl *event, EventTime time); 48 49 // Initialize the loop, code removed from the constructor. 50 virtual int Initialize() = 0; 51 bool IsInLoopThread(bool &started) const; 52 53 private: 54 virtual int Prepare(const std::set<EventImpl *> &polling) = 0; 55 virtual int Poll(EventTime sleepTime) = 0; 56 virtual int WakeUp() = 0; 57 virtual int Exit(const std::set<EventImpl *> &polling) = 0; 58 virtual int AddEvent(EventImpl *event) = 0; 59 virtual int RemoveEvent(EventImpl *event) = 0; 60 virtual int ModifyEvent(EventImpl *event, bool isAdd, EventsMask events) = 0; 61 virtual EventTime GetTime() const; 62 63 template<typename T> 64 int QueueRequest(int type, EventImpl *event, T argument); 65 int SendRequestToLoop(EventRequest *eventRequest); 66 bool EventObjectExists(EventImpl *event) const; 67 bool EventFdExists(const EventImpl *event) const; 68 int AddEventObject(EventImpl *event, EventTime now); 69 int RemoveEventObject(EventImpl *event); 70 int ModifyEventObject(EventImpl *event, bool isAdd, EventsMask events); 71 int ModifyEventObject(EventImpl *event, EventTime timeout); 72 void ProcessRequest(std::list<EventRequest *> &requests); 73 int ProcessRequest(); 74 EventTime CalSleepTime() const; 75 int DispatchAll(); 76 void CleanLoop(); 77 void OnKillLoop(); 78 79 std::list<EventRequest *> requests_; 80 std::set<EventImpl *> polling_; 81 bool pollingSetChanged_; 82 std::thread::id loopThread_; 83 volatile bool running_; 84 }; 85 } 86 87 #endif // EVENT_LOOP_IMPL_H 88