1 /* 2 * Copyright 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 #pragma once 18 19 #include <ftl/small_vector.h> 20 #include <semaphore.h> 21 #include <thread> 22 23 #include "LocklessQueue.h" 24 25 namespace android { 26 27 // Executes tasks off the main thread. 28 class BackgroundExecutor { 29 public: 30 ~BackgroundExecutor(); 31 getInstance()32 static BackgroundExecutor& getInstance() { 33 static BackgroundExecutor instance(true); 34 return instance; 35 } 36 getLowPriorityInstance()37 static BackgroundExecutor& getLowPriorityInstance() { 38 static BackgroundExecutor instance(false); 39 return instance; 40 } 41 42 using Callbacks = ftl::SmallVector<std::function<void()>, 10>; 43 // Queues callbacks onto a work queue to be executed by a background thread. 44 // This is safe to call from multiple threads. 45 void sendCallbacks(Callbacks&& tasks); 46 void flushQueue(); 47 48 private: 49 BackgroundExecutor(bool highPriority); 50 51 sem_t mSemaphore; 52 std::atomic_bool mDone = false; 53 54 LocklessQueue<Callbacks> mCallbacksQueue; 55 std::thread mThread; 56 }; 57 58 } // namespace android 59