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 <utils/Singleton.h> 22 #include <thread> 23 24 #include "LocklessQueue.h" 25 26 namespace android { 27 28 // Executes tasks off the main thread. 29 class BackgroundExecutor : public Singleton<BackgroundExecutor> { 30 public: 31 BackgroundExecutor(); 32 ~BackgroundExecutor(); 33 using Callbacks = ftl::SmallVector<std::function<void()>, 10>; 34 // Queues callbacks onto a work queue to be executed by a background thread. 35 // This is safe to call from multiple threads. 36 void sendCallbacks(Callbacks&& tasks); 37 void flushQueue(); 38 39 private: 40 sem_t mSemaphore; 41 std::atomic_bool mDone = false; 42 43 LocklessQueue<Callbacks> mCallbacksQueue; 44 std::thread mThread; 45 }; 46 47 } // namespace android 48