blob: 66b7d7a1fc865b180f94bb60b777511efc98fa2a [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 <utils/Singleton.h>
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080022#include <thread>
23
Patrick Williams13310b82023-05-17 14:40:18 -050024#include "LocklessQueue.h"
25
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080026namespace android {
27
28// Executes tasks off the main thread.
29class BackgroundExecutor : public Singleton<BackgroundExecutor> {
30public:
31 BackgroundExecutor();
32 ~BackgroundExecutor();
Alec Mouri8d7d0f42022-05-10 23:33:40 +000033 using Callbacks = ftl::SmallVector<std::function<void()>, 10>;
34 // Queues callbacks onto a work queue to be executed by a background thread.
Patrick Williams13310b82023-05-17 14:40:18 -050035 // This is safe to call from multiple threads.
Alec Mouri8d7d0f42022-05-10 23:33:40 +000036 void sendCallbacks(Callbacks&& tasks);
Patrick Williamsacd22582023-07-12 13:47:28 -050037 void flushQueue();
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080038
39private:
Alec Mouri8d7d0f42022-05-10 23:33:40 +000040 sem_t mSemaphore;
41 std::atomic_bool mDone = false;
42
Patrick Williams13310b82023-05-17 14:40:18 -050043 LocklessQueue<Callbacks> mCallbacksQueue;
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080044 std::thread mThread;
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080045};
46
47} // namespace android