| Ana Krulec | 70d15b1b | 2020-12-01 10:05:15 -0800 | [diff] [blame] | 1 | /* | 
|  | 2 | * Copyright 2020 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 <log/log.h> | 
|  | 20 |  | 
|  | 21 | #include <condition_variable> | 
|  | 22 | #include <functional> | 
|  | 23 | #include <future> | 
|  | 24 | #include <mutex> | 
|  | 25 | #include <queue> | 
|  | 26 |  | 
|  | 27 | namespace android { | 
|  | 28 | namespace renderengine { | 
|  | 29 | namespace skia { | 
|  | 30 |  | 
|  | 31 | namespace { | 
|  | 32 | #define PREVENT_COPY_AND_ASSIGN(Type) \ | 
|  | 33 | private:                              \ | 
|  | 34 | Type(const Type&) = delete;       \ | 
|  | 35 | void operator=(const Type&) = delete | 
|  | 36 | } // namespace | 
|  | 37 |  | 
|  | 38 | /** | 
|  | 39 | * Shamelessly copied from HWUI to execute Skia Capturing on the back thread in | 
|  | 40 | * a safe manner. | 
|  | 41 | */ | 
|  | 42 | class CommonPool { | 
|  | 43 | PREVENT_COPY_AND_ASSIGN(CommonPool); | 
|  | 44 |  | 
|  | 45 | public: | 
|  | 46 | using Task = std::function<void()>; | 
|  | 47 | static constexpr auto THREAD_COUNT = 2; | 
|  | 48 | static constexpr auto QUEUE_SIZE = 128; | 
|  | 49 |  | 
|  | 50 | static void post(Task&& func); | 
|  | 51 |  | 
|  | 52 | private: | 
|  | 53 | static CommonPool& instance(); | 
|  | 54 |  | 
|  | 55 | CommonPool(); | 
|  | 56 | ~CommonPool() {} | 
|  | 57 |  | 
|  | 58 | void enqueue(Task&&); | 
|  | 59 |  | 
|  | 60 | void workerLoop(); | 
|  | 61 |  | 
|  | 62 | std::mutex mLock; | 
|  | 63 | std::condition_variable mCondition; | 
|  | 64 | int mWaitingThreads = 0; | 
|  | 65 | std::queue<Task> mWorkQueue; | 
|  | 66 | }; | 
|  | 67 |  | 
|  | 68 | } // namespace skia | 
|  | 69 | } // namespace renderengine | 
|  | 70 | } // namespace android |