Ytai Ben-Tsvi | 1ea62c9 | 2021-11-10 14:38:27 -0800 | [diff] [blame] | 1 | /* |
| 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> |
Andy Hung | a2a1ac3 | 2022-03-18 16:12:11 -0700 | [diff] [blame] | 20 | #include <sstream> |
| 21 | #include <unistd.h> |
| 22 | #include <vector> |
Ytai Ben-Tsvi | 1ea62c9 | 2021-11-10 14:38:27 -0800 | [diff] [blame] | 23 | |
| 24 | #include <mediautils/TimerThread.h> |
| 25 | #include <utils/ThreadDefs.h> |
| 26 | |
Andy Hung | a2a1ac3 | 2022-03-18 16:12:11 -0700 | [diff] [blame] | 27 | namespace android::mediautils { |
Ytai Ben-Tsvi | 1ea62c9 | 2021-11-10 14:38:27 -0800 | [diff] [blame] | 28 | |
Andy Hung | a2a1ac3 | 2022-03-18 16:12:11 -0700 | [diff] [blame] | 29 | extern std::string formatTime(std::chrono::system_clock::time_point t); |
| 30 | extern std::string_view timeSuffix(std::string_view time1, std::string_view time2); |
| 31 | |
| 32 | TimerThread::Handle TimerThread::scheduleTask( |
| 33 | std::string tag, std::function<void()>&& func, std::chrono::milliseconds timeout) { |
| 34 | const auto now = std::chrono::system_clock::now(); |
| 35 | std::shared_ptr<const Request> request{ |
| 36 | new Request{ now, now + timeout, gettid(), std::move(tag) }}; |
| 37 | return mMonitorThread.add(std::move(request), std::move(func), timeout); |
Ytai Ben-Tsvi | 1ea62c9 | 2021-11-10 14:38:27 -0800 | [diff] [blame] | 38 | } |
| 39 | |
Andy Hung | a2a1ac3 | 2022-03-18 16:12:11 -0700 | [diff] [blame] | 40 | TimerThread::Handle TimerThread::trackTask(std::string tag) { |
| 41 | const auto now = std::chrono::system_clock::now(); |
| 42 | std::shared_ptr<const Request> request{ |
| 43 | new Request{ now, now, gettid(), std::move(tag) }}; |
| 44 | return mNoTimeoutMap.add(std::move(request)); |
| 45 | } |
| 46 | |
| 47 | bool TimerThread::cancelTask(Handle handle) { |
| 48 | std::shared_ptr<const Request> request = mNoTimeoutMap.isValidHandle(handle) ? |
| 49 | mNoTimeoutMap.remove(handle) : mMonitorThread.remove(handle); |
| 50 | if (!request) return false; |
| 51 | mRetiredQueue.add(std::move(request)); |
| 52 | return true; |
| 53 | } |
| 54 | |
| 55 | std::string TimerThread::toString(size_t retiredCount) const { |
| 56 | return std::string("now ") |
| 57 | .append(formatTime(std::chrono::system_clock::now())) |
| 58 | .append("\npending [ ") |
| 59 | .append(pendingToString()) |
| 60 | .append(" ]\ntimeout [ ") |
| 61 | .append(timeoutToString()) |
| 62 | .append(" ]\nretired [ ") |
| 63 | .append(retiredToString(retiredCount)) |
| 64 | .append(" ]"); |
| 65 | } |
| 66 | |
| 67 | std::vector<std::shared_ptr<const TimerThread::Request>> TimerThread::getPendingRequests() const { |
| 68 | constexpr size_t kEstimatedPendingRequests = 8; // approx 128 byte alloc. |
| 69 | std::vector<std::shared_ptr<const Request>> pendingRequests; |
| 70 | pendingRequests.reserve(kEstimatedPendingRequests); // preallocate vector out of lock. |
| 71 | |
| 72 | // following are internally locked calls, which add to our local pendingRequests. |
| 73 | mMonitorThread.copyRequests(pendingRequests); |
| 74 | mNoTimeoutMap.copyRequests(pendingRequests); |
| 75 | |
| 76 | // Sort in order of scheduled time. |
| 77 | std::sort(pendingRequests.begin(), pendingRequests.end(), |
| 78 | [](const std::shared_ptr<const Request>& r1, |
| 79 | const std::shared_ptr<const Request>& r2) { |
| 80 | return r1->scheduled < r2->scheduled; |
| 81 | }); |
| 82 | return pendingRequests; |
| 83 | } |
| 84 | |
| 85 | std::string TimerThread::pendingToString() const { |
| 86 | return requestsToString(getPendingRequests()); |
| 87 | } |
| 88 | |
| 89 | std::string TimerThread::retiredToString(size_t n) const { |
| 90 | std::vector<std::shared_ptr<const Request>> retiredRequests; |
| 91 | mRetiredQueue.copyRequests(retiredRequests, n); |
| 92 | |
| 93 | // Dump to string |
| 94 | return requestsToString(retiredRequests); |
| 95 | } |
| 96 | |
| 97 | std::string TimerThread::timeoutToString(size_t n) const { |
| 98 | std::vector<std::shared_ptr<const Request>> timeoutRequests; |
| 99 | mTimeoutQueue.copyRequests(timeoutRequests, n); |
| 100 | |
| 101 | // Dump to string |
| 102 | return requestsToString(timeoutRequests); |
| 103 | } |
| 104 | |
| 105 | std::string TimerThread::Request::toString() const { |
| 106 | const auto scheduledString = formatTime(scheduled); |
| 107 | const auto deadlineString = formatTime(deadline); |
| 108 | return std::string(tag) |
| 109 | .append(" scheduled ").append(scheduledString) |
| 110 | .append(" deadline ").append(timeSuffix(scheduledString, deadlineString)) |
| 111 | .append(" tid ").append(std::to_string(tid)); |
| 112 | } |
| 113 | |
| 114 | void TimerThread::RequestQueue::add(std::shared_ptr<const Request> request) { |
| 115 | std::lock_guard lg(mRQMutex); |
| 116 | mRequestQueue.emplace_back(std::chrono::system_clock::now(), std::move(request)); |
| 117 | if (mRequestQueue.size() > mRequestQueueMax) { |
| 118 | mRequestQueue.pop_front(); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | void TimerThread::RequestQueue::copyRequests( |
| 123 | std::vector<std::shared_ptr<const Request>>& requests, size_t n) const { |
| 124 | std::lock_guard lg(mRQMutex); |
| 125 | const size_t size = mRequestQueue.size(); |
| 126 | size_t i = n >= size ? 0 : size - n; |
| 127 | for (; i < size; ++i) { |
| 128 | const auto &[time, request] = mRequestQueue[i]; |
| 129 | requests.emplace_back(request); |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | bool TimerThread::NoTimeoutMap::isValidHandle(Handle handle) const { |
| 134 | return handle > getIndexedHandle(mNoTimeoutRequests); |
| 135 | } |
| 136 | |
| 137 | TimerThread::Handle TimerThread::NoTimeoutMap::add(std::shared_ptr<const Request> request) { |
| 138 | std::lock_guard lg(mNTMutex); |
| 139 | // A unique handle is obtained by mNoTimeoutRequests.fetch_add(1), |
| 140 | // This need not be under a lock, but we do so anyhow. |
| 141 | const Handle handle = getIndexedHandle(mNoTimeoutRequests++); |
| 142 | mMap[handle] = request; |
| 143 | return handle; |
| 144 | } |
| 145 | |
| 146 | std::shared_ptr<const TimerThread::Request> TimerThread::NoTimeoutMap::remove(Handle handle) { |
| 147 | std::lock_guard lg(mNTMutex); |
| 148 | auto it = mMap.find(handle); |
| 149 | if (it == mMap.end()) return {}; |
| 150 | auto request = it->second; |
| 151 | mMap.erase(it); |
| 152 | return request; |
| 153 | } |
| 154 | |
| 155 | void TimerThread::NoTimeoutMap::copyRequests( |
| 156 | std::vector<std::shared_ptr<const Request>>& requests) const { |
| 157 | std::lock_guard lg(mNTMutex); |
| 158 | for (const auto &[handle, request] : mMap) { |
| 159 | requests.emplace_back(request); |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | TimerThread::Handle TimerThread::MonitorThread::getUniqueHandle_l( |
| 164 | std::chrono::milliseconds timeout) { |
| 165 | // To avoid key collisions, advance by 1 tick until the key is unique. |
| 166 | auto deadline = std::chrono::steady_clock::now() + timeout; |
| 167 | for (; mMonitorRequests.find(deadline) != mMonitorRequests.end(); |
| 168 | deadline += std::chrono::steady_clock::duration(1)) |
| 169 | ; |
| 170 | return deadline; |
| 171 | } |
| 172 | |
| 173 | TimerThread::MonitorThread::MonitorThread(RequestQueue& timeoutQueue) |
| 174 | : mTimeoutQueue(timeoutQueue) |
| 175 | , mThread([this] { threadFunc(); }) { |
| 176 | pthread_setname_np(mThread.native_handle(), "TimerThread"); |
| 177 | pthread_setschedprio(mThread.native_handle(), PRIORITY_URGENT_AUDIO); |
| 178 | } |
| 179 | |
| 180 | TimerThread::MonitorThread::~MonitorThread() { |
Ytai Ben-Tsvi | 1ea62c9 | 2021-11-10 14:38:27 -0800 | [diff] [blame] | 181 | { |
| 182 | std::lock_guard _l(mMutex); |
| 183 | mShouldExit = true; |
| 184 | mCond.notify_all(); |
| 185 | } |
| 186 | mThread.join(); |
| 187 | } |
| 188 | |
Andy Hung | a2a1ac3 | 2022-03-18 16:12:11 -0700 | [diff] [blame] | 189 | void TimerThread::MonitorThread::threadFunc() { |
Ytai Ben-Tsvi | 1ea62c9 | 2021-11-10 14:38:27 -0800 | [diff] [blame] | 190 | std::unique_lock _l(mMutex); |
Ytai Ben-Tsvi | 1ea62c9 | 2021-11-10 14:38:27 -0800 | [diff] [blame] | 191 | while (!mShouldExit) { |
| 192 | if (!mMonitorRequests.empty()) { |
Andy Hung | a2a1ac3 | 2022-03-18 16:12:11 -0700 | [diff] [blame] | 193 | Handle nextDeadline = mMonitorRequests.begin()->first; |
Ytai Ben-Tsvi | 1ea62c9 | 2021-11-10 14:38:27 -0800 | [diff] [blame] | 194 | if (nextDeadline < std::chrono::steady_clock::now()) { |
Andy Hung | a2a1ac3 | 2022-03-18 16:12:11 -0700 | [diff] [blame] | 195 | // Deadline has expired, handle the request. |
| 196 | { |
| 197 | auto node = mMonitorRequests.extract(mMonitorRequests.begin()); |
| 198 | _l.unlock(); |
| 199 | // We add Request to retired queue early so that it can be dumped out. |
| 200 | mTimeoutQueue.add(std::move(node.mapped().first)); |
| 201 | node.mapped().second(); // Caution: we don't hold lock here - but do we care? |
| 202 | // this is the timeout case! We will crash soon, |
| 203 | // maybe before returning. |
| 204 | // anything left over is released here outside lock. |
| 205 | } |
| 206 | // reacquire the lock - if something was added, we loop immediately to check. |
| 207 | _l.lock(); |
| 208 | continue; |
Ytai Ben-Tsvi | 1ea62c9 | 2021-11-10 14:38:27 -0800 | [diff] [blame] | 209 | } |
| 210 | mCond.wait_until(_l, nextDeadline); |
| 211 | } else { |
| 212 | mCond.wait(_l); |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | |
Andy Hung | a2a1ac3 | 2022-03-18 16:12:11 -0700 | [diff] [blame] | 217 | TimerThread::Handle TimerThread::MonitorThread::add( |
| 218 | std::shared_ptr<const Request> request, std::function<void()>&& func, |
| 219 | std::chrono::milliseconds timeout) { |
| 220 | std::lock_guard _l(mMutex); |
| 221 | const Handle handle = getUniqueHandle_l(timeout); |
| 222 | mMonitorRequests.emplace(handle, std::make_pair(std::move(request), std::move(func))); |
| 223 | mCond.notify_all(); |
| 224 | return handle; |
| 225 | } |
| 226 | |
| 227 | std::shared_ptr<const TimerThread::Request> TimerThread::MonitorThread::remove(Handle handle) { |
| 228 | std::unique_lock ul(mMutex); |
| 229 | const auto it = mMonitorRequests.find(handle); |
| 230 | if (it == mMonitorRequests.end()) { |
| 231 | return {}; |
| 232 | } |
| 233 | std::shared_ptr<const TimerThread::Request> request = std::move(it->second.first); |
| 234 | std::function<void()> func = std::move(it->second.second); |
| 235 | mMonitorRequests.erase(it); |
| 236 | ul.unlock(); // manually release lock here so func is released outside of lock. |
| 237 | return request; |
| 238 | } |
| 239 | |
| 240 | void TimerThread::MonitorThread::copyRequests( |
| 241 | std::vector<std::shared_ptr<const Request>>& requests) const { |
| 242 | std::lock_guard lg(mMutex); |
| 243 | for (const auto &[deadline, monitorpair] : mMonitorRequests) { |
| 244 | requests.emplace_back(monitorpair.first); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | } // namespace android::mediautils |