blob: 1b5fadd67499b3d578329ac5fb359b7b96cbff26 [file] [log] [blame]
Vishnu Nair34eb9ca2021-11-18 15:23:23 -08001/*
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
Alec Mouri8d7d0f42022-05-10 23:33:40 +000019#include <ftl/small_vector.h>
20#include <semaphore.h>
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080021#include <thread>
22
Patrick Williams13310b82023-05-17 14:40:18 -050023#include "LocklessQueue.h"
24
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080025namespace android {
26
27// Executes tasks off the main thread.
Pascal Mütschardd0afeb72024-03-13 12:08:26 +010028class BackgroundExecutor {
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080029public:
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080030 ~BackgroundExecutor();
Pascal Mütschardd0afeb72024-03-13 12:08:26 +010031
32 static BackgroundExecutor& getInstance() {
33 static BackgroundExecutor instance(true);
34 return instance;
35 }
36
37 static BackgroundExecutor& getLowPriorityInstance() {
38 static BackgroundExecutor instance(false);
39 return instance;
40 }
41
Alec Mouri8d7d0f42022-05-10 23:33:40 +000042 using Callbacks = ftl::SmallVector<std::function<void()>, 10>;
43 // Queues callbacks onto a work queue to be executed by a background thread.
Patrick Williams13310b82023-05-17 14:40:18 -050044 // This is safe to call from multiple threads.
Alec Mouri8d7d0f42022-05-10 23:33:40 +000045 void sendCallbacks(Callbacks&& tasks);
Patrick Williamsacd22582023-07-12 13:47:28 -050046 void flushQueue();
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080047
48private:
Pascal Mütschardd0afeb72024-03-13 12:08:26 +010049 BackgroundExecutor(bool highPriority);
50
Alec Mouri8d7d0f42022-05-10 23:33:40 +000051 sem_t mSemaphore;
52 std::atomic_bool mDone = false;
53
Patrick Williams13310b82023-05-17 14:40:18 -050054 LocklessQueue<Callbacks> mCallbacksQueue;
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080055 std::thread mThread;
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080056};
57
58} // namespace android