blob: b3fec1fb36c353a4ce968149af8400514eb01d61 [file] [log] [blame]
John Reckf8441e62017-10-23 13:10:41 -07001/*
2 * Copyright (C) 2017 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#ifndef HWUI_THREADBASE_H
18#define HWUI_THREADBASE_H
19
20#include "WorkQueue.h"
21#include "utils/Macros.h"
22
23#include <utils/Looper.h>
24#include <utils/Thread.h>
25
26#include <algorithm>
27
28namespace android::uirenderer {
29
30class ThreadBase : protected Thread {
31 PREVENT_COPY_AND_ASSIGN(ThreadBase);
32
33public:
John Reck1bcacfd2017-11-03 10:12:19 -070034 ThreadBase() : mLooper(new Looper(false)), mQueue([this]() { mLooper->wake(); }, mLock) {}
John Reckf8441e62017-10-23 13:10:41 -070035
36 WorkQueue& queue() { return mQueue; }
37
38 void requestExit() {
39 Thread::requestExit();
40 mLooper->wake();
41 }
42
John Reck1bcacfd2017-11-03 10:12:19 -070043 void start(const char* name = "ThreadBase") { Thread::run(name); }
John Reckf8441e62017-10-23 13:10:41 -070044
John Reck1bcacfd2017-11-03 10:12:19 -070045 void join() { Thread::join(); }
John Reckf8441e62017-10-23 13:10:41 -070046
47protected:
48 void waitForWork() {
49 nsecs_t nextWakeup;
50 {
51 std::unique_lock lock{mLock};
52 nextWakeup = mQueue.nextWakeup(lock);
53 }
54 int timeout = -1;
55 if (nextWakeup < std::numeric_limits<nsecs_t>::max()) {
56 timeout = ns2ms(nextWakeup - WorkQueue::clock::now());
57 if (timeout < 0) timeout = 0;
58 }
59 int result = mLooper->pollOnce(timeout);
John Reck1bcacfd2017-11-03 10:12:19 -070060 LOG_ALWAYS_FATAL_IF(result == Looper::POLL_ERROR, "RenderThread Looper POLL_ERROR!");
John Reckf8441e62017-10-23 13:10:41 -070061 }
62
John Reck1bcacfd2017-11-03 10:12:19 -070063 void processQueue() { mQueue.process(); }
John Reckf8441e62017-10-23 13:10:41 -070064
65 virtual bool threadLoop() override {
66 while (!exitPending()) {
67 waitForWork();
68 processQueue();
69 }
70 return false;
71 }
72
73 sp<Looper> mLooper;
74
75private:
76 WorkQueue mQueue;
77 std::mutex mLock;
78};
79
John Reck1bcacfd2017-11-03 10:12:19 -070080} // namespace android::uirenderer
John Reckf8441e62017-10-23 13:10:41 -070081
John Reck1bcacfd2017-11-03 10:12:19 -070082#endif // HWUI_THREADBASE_H