blob: 3c95798dea8deb17082bed4e5c8d38a1e94f362a [file] [log] [blame]
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -08001/*
2 * Copyright (C) 2021 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#define LOG_TAG "TimerThread"
18
19#include <optional>
20
21#include <mediautils/TimerThread.h>
22#include <utils/ThreadDefs.h>
23
24namespace android {
25
26TimerThread::TimerThread() : mThread([this] { threadFunc(); }) {
27 pthread_setname_np(mThread.native_handle(), "TimeCheckThread");
28 pthread_setschedprio(mThread.native_handle(), PRIORITY_URGENT_AUDIO);
29}
30
31TimerThread::~TimerThread() {
32 {
33 std::lock_guard _l(mMutex);
34 mShouldExit = true;
35 mCond.notify_all();
36 }
37 mThread.join();
38}
39
40TimerThread::Handle TimerThread::scheduleTaskAtDeadline(std::function<void()>&& func,
41 TimePoint deadline) {
42 std::lock_guard _l(mMutex);
43
44 // To avoid key collisions, advance by 1 tick until the key is unique.
45 for (; mMonitorRequests.find(deadline) != mMonitorRequests.end();
46 deadline += TimePoint::duration(1))
47 ;
48 mMonitorRequests.emplace(deadline, std::move(func));
49 mCond.notify_all();
50 return deadline;
51}
52
53void TimerThread::cancelTask(Handle handle) {
54 std::lock_guard _l(mMutex);
55 mMonitorRequests.erase(handle);
56}
57
58void TimerThread::threadFunc() {
59 std::unique_lock _l(mMutex);
60
61 while (!mShouldExit) {
62 if (!mMonitorRequests.empty()) {
63 TimePoint nextDeadline = mMonitorRequests.begin()->first;
64 if (nextDeadline < std::chrono::steady_clock::now()) {
65 // Deadline expired.
66 mMonitorRequests.begin()->second();
67 mMonitorRequests.erase(mMonitorRequests.begin());
68 }
69 mCond.wait_until(_l, nextDeadline);
70 } else {
71 mCond.wait(_l);
72 }
73 }
74}
75
76} // namespace android