1 /* 2 * Copyright 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include "TimeKeeper.h" 20 21 #include <android-base/thread_annotations.h> 22 #include <array> 23 #include <thread> 24 25 namespace android::scheduler { 26 27 class Timer : public TimeKeeper { 28 public: 29 Timer(); 30 ~Timer(); 31 nsecs_t now() const final; 32 33 // NB: alarmIn and alarmCancel are threadsafe; with the last-returning function being effectual 34 // Most users will want to serialize thes calls so as to be aware of the timer state. 35 void alarmIn(std::function<void()> const& cb, nsecs_t fireIn) final; 36 void alarmCancel() final; 37 void dump(std::string& result) const final; 38 39 private: 40 enum class DebugState { Reset, Running, Waiting, Reading, InCallback, Terminated }; 41 void reset(); 42 void cleanup(); 43 void setDebugState(DebugState state) EXCLUDES(mMutex); 44 const char* strDebugState(DebugState state) const; 45 46 int mTimerFd = -1; 47 int mEpollFd = -1; 48 std::array<int, 2> mPipes = {-1, -1}; 49 50 std::thread mDispatchThread; 51 void threadMain(); 52 bool dispatch(); 53 void endDispatch(); 54 55 mutable std::mutex mMutex; 56 std::function<void()> mCallback GUARDED_BY(mMutex); 57 DebugState mDebugState GUARDED_BY(mMutex); 58 }; 59 60 } // namespace android::scheduler 61