blob: 628d800bc7b1bad7044a2171f79548befb60cc64 [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:
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040 enum class DebugState {
41 Reset,
42 Running,
43 Waiting,
44 Reading,
45 InCallback,
46 Terminated,
47
48 ftl_last = Terminated
49 };
50
Ady Abraham75398722020-04-07 14:08:45 -070051 void reset();
52 void cleanup();
53 void setDebugState(DebugState state) EXCLUDES(mMutex);
Ady Abraham75398722020-04-07 14:08:45 -070054
55 int mTimerFd = -1;
56 int mEpollFd = -1;
57 std::array<int, 2> mPipes = {-1, -1};
Kevin DuBoiscc27b502019-11-13 09:40:07 -080058
59 std::thread mDispatchThread;
Ady Abraham75398722020-04-07 14:08:45 -070060 void threadMain();
61 bool dispatch();
Kevin DuBoiscc27b502019-11-13 09:40:07 -080062 void endDispatch();
63
Ady Abraham75398722020-04-07 14:08:45 -070064 mutable std::mutex mMutex;
Kevin DuBoiscc27b502019-11-13 09:40:07 -080065 std::function<void()> mCallback GUARDED_BY(mMutex);
Ady Abraham75398722020-04-07 14:08:45 -070066 DebugState mDebugState GUARDED_BY(mMutex);
Kevin DuBoiscc27b502019-11-13 09:40:07 -080067};
68
69} // namespace android::scheduler