blob: 69ce07943724a43a75af1707995779db853a704d [file] [log] [blame]
Kevin DuBoiscc27b502019-11-13 09:40:07 -08001/*
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
25namespace android::scheduler {
26
27class Timer : public TimeKeeper {
28public:
29 Timer();
30 ~Timer();
31 nsecs_t now() const final;
32
Ady Abrahamb491c902020-08-15 15:47:56 -070033 // NB: alarmAt and alarmCancel are threadsafe; with the last-returning function being effectual
Kevin DuBoiscc27b502019-11-13 09:40:07 -080034 // Most users will want to serialize thes calls so as to be aware of the timer state.
Ady Abrahamb491c902020-08-15 15:47:56 -070035 void alarmAt(std::function<void()> const& cb, nsecs_t time) final;
Kevin DuBoiscc27b502019-11-13 09:40:07 -080036 void alarmCancel() final;
Ady Abraham75398722020-04-07 14:08:45 -070037 void dump(std::string& result) const final;
Kevin DuBoiscc27b502019-11-13 09:40:07 -080038
39private:
Ady Abraham75398722020-04-07 14:08:45 -070040 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};
Kevin DuBoiscc27b502019-11-13 09:40:07 -080049
50 std::thread mDispatchThread;
Ady Abraham75398722020-04-07 14:08:45 -070051 void threadMain();
52 bool dispatch();
Kevin DuBoiscc27b502019-11-13 09:40:07 -080053 void endDispatch();
54
Ady Abraham75398722020-04-07 14:08:45 -070055 mutable std::mutex mMutex;
Kevin DuBoiscc27b502019-11-13 09:40:07 -080056 std::function<void()> mCallback GUARDED_BY(mMutex);
Ady Abraham75398722020-04-07 14:08:45 -070057 DebugState mDebugState GUARDED_BY(mMutex);
Kevin DuBoiscc27b502019-11-13 09:40:07 -080058};
59
60} // namespace android::scheduler