John Reck | f8441e6 | 2017-10-23 13:10:41 -0700 | [diff] [blame] | 1 | /* |
| 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 | |
| 28 | namespace android::uirenderer { |
| 29 | |
| 30 | class ThreadBase : protected Thread { |
| 31 | PREVENT_COPY_AND_ASSIGN(ThreadBase); |
| 32 | |
| 33 | public: |
| 34 | ThreadBase() |
| 35 | : mLooper(new Looper(false)) |
| 36 | , mQueue([this](){ mLooper->wake(); }, mLock) |
| 37 | {} |
| 38 | |
| 39 | WorkQueue& queue() { return mQueue; } |
| 40 | |
| 41 | void requestExit() { |
| 42 | Thread::requestExit(); |
| 43 | mLooper->wake(); |
| 44 | } |
| 45 | |
| 46 | void start(const char* name = "ThreadBase") { |
| 47 | Thread::run(name); |
| 48 | } |
| 49 | |
| 50 | void join() { |
| 51 | Thread::join(); |
| 52 | } |
| 53 | |
| 54 | protected: |
| 55 | void waitForWork() { |
| 56 | nsecs_t nextWakeup; |
| 57 | { |
| 58 | std::unique_lock lock{mLock}; |
| 59 | nextWakeup = mQueue.nextWakeup(lock); |
| 60 | } |
| 61 | int timeout = -1; |
| 62 | if (nextWakeup < std::numeric_limits<nsecs_t>::max()) { |
| 63 | timeout = ns2ms(nextWakeup - WorkQueue::clock::now()); |
| 64 | if (timeout < 0) timeout = 0; |
| 65 | } |
| 66 | int result = mLooper->pollOnce(timeout); |
| 67 | LOG_ALWAYS_FATAL_IF(result == Looper::POLL_ERROR, |
| 68 | "RenderThread Looper POLL_ERROR!"); |
| 69 | } |
| 70 | |
| 71 | void processQueue() { |
| 72 | mQueue.process(); |
| 73 | } |
| 74 | |
| 75 | virtual bool threadLoop() override { |
| 76 | while (!exitPending()) { |
| 77 | waitForWork(); |
| 78 | processQueue(); |
| 79 | } |
| 80 | return false; |
| 81 | } |
| 82 | |
| 83 | sp<Looper> mLooper; |
| 84 | |
| 85 | private: |
| 86 | WorkQueue mQueue; |
| 87 | std::mutex mLock; |
| 88 | }; |
| 89 | |
| 90 | } // namespace android::uirenderer |
| 91 | |
| 92 | |
| 93 | #endif //HWUI_THREADBASE_H |