blob: 6db7dda7aa05b7cca16d4a46dbae0c151e129ca6 [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
Vishnu Nair03ccbd62021-12-01 17:21:16 -080019#include <android-base/thread_annotations.h>
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080020#include <utils/Singleton.h>
21#include <condition_variable>
22#include <mutex>
23#include <queue>
24#include <thread>
25
26namespace android {
27
28// Executes tasks off the main thread.
29class BackgroundExecutor : public Singleton<BackgroundExecutor> {
30public:
31 BackgroundExecutor();
32 ~BackgroundExecutor();
33 void execute(std::function<void()>);
34
35private:
36 std::mutex mMutex;
Vishnu Nair03ccbd62021-12-01 17:21:16 -080037 std::condition_variable mWorkAvailableCv GUARDED_BY(mMutex);
38 bool mDone GUARDED_BY(mMutex) = false;
39 std::vector<std::function<void()>> mTasks GUARDED_BY(mMutex);
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080040 std::thread mThread;
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080041};
42
43} // namespace android