blob: 3663cdb0eca0a8e30cc2b19d3e7598026f515473 [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);
Jaineel Mehtaac331c52021-11-29 21:38:10 +000035 mWorkAvailableCv.wait(lock, [&]() { return mDone || !mTasks.empty(); });
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080036 tasks = std::move(mTasks);
37 mTasks.clear();
38 done = mDone;
39 } // unlock mMutex
40
41 for (auto& task : tasks) {
42 task();
43 }
44 }
45 });
46}
47
48BackgroundExecutor::~BackgroundExecutor() {
49 {
Jaineel Mehtaac331c52021-11-29 21:38:10 +000050 std::unique_lock lock(mMutex);
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080051 mDone = true;
52 mWorkAvailableCv.notify_all();
53 }
54 if (mThread.joinable()) {
55 mThread.join();
56 }
57}
58
59void BackgroundExecutor::execute(std::function<void()> task) {
Jaineel Mehtaac331c52021-11-29 21:38:10 +000060 std::unique_lock lock(mMutex);
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080061 mTasks.emplace_back(std::move(task));
62 mWorkAvailableCv.notify_all();
63}
64
65} // namespace android