blob: de8e6b380f05df80113e0efc18d92488d43f2ec2 [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//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "BackgroundExecutor"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22#include "BackgroundExecutor.h"
23
24namespace android {
25
26ANDROID_SINGLETON_STATIC_INSTANCE(BackgroundExecutor);
27
28BackgroundExecutor::BackgroundExecutor() : Singleton<BackgroundExecutor>() {
29 mThread = std::thread([&]() {
30 bool done = false;
31 while (!done) {
32 std::vector<std::function<void()>> tasks;
33 {
34 std::unique_lock lock(mMutex);
Vishnu Nair42a27b52021-11-18 15:35:22 -080035 android::base::ScopedLockAssertion assumeLock(mMutex);
36 mWorkAvailableCv.wait(lock,
37 [&]() REQUIRES(mMutex) { return mDone || !mTasks.empty(); });
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080038 tasks = std::move(mTasks);
39 mTasks.clear();
40 done = mDone;
41 } // unlock mMutex
42
43 for (auto& task : tasks) {
44 task();
45 }
46 }
47 });
48}
49
50BackgroundExecutor::~BackgroundExecutor() {
51 {
Vishnu Nair42a27b52021-11-18 15:35:22 -080052 std::scoped_lock lock(mMutex);
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080053 mDone = true;
54 mWorkAvailableCv.notify_all();
55 }
56 if (mThread.joinable()) {
57 mThread.join();
58 }
59}
60
61void BackgroundExecutor::execute(std::function<void()> task) {
Vishnu Nair42a27b52021-11-18 15:35:22 -080062 std::scoped_lock lock(mMutex);
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080063 mTasks.emplace_back(std::move(task));
64 mWorkAvailableCv.notify_all();
65}
66
67} // namespace android