blob: 6ddf790d47ed68b282a0f4c889fdd624c02db136 [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
Alec Mouri8d7d0f42022-05-10 23:33:40 +000022#include <utils/Log.h>
23
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080024#include "BackgroundExecutor.h"
25
26namespace android {
27
28ANDROID_SINGLETON_STATIC_INSTANCE(BackgroundExecutor);
29
30BackgroundExecutor::BackgroundExecutor() : Singleton<BackgroundExecutor>() {
Patrick Williams13310b82023-05-17 14:40:18 -050031 // mSemaphore must be initialized before any calls to
32 // BackgroundExecutor::sendCallbacks. For this reason, we initialize it
33 // within the constructor instead of within mThread.
34 LOG_ALWAYS_FATAL_IF(sem_init(&mSemaphore, 0, 0), "sem_init failed");
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080035 mThread = std::thread([&]() {
Alec Mouri8d7d0f42022-05-10 23:33:40 +000036 while (!mDone) {
37 LOG_ALWAYS_FATAL_IF(sem_wait(&mSemaphore), "sem_wait failed (%d)", errno);
Patrick Williams13310b82023-05-17 14:40:18 -050038 auto callbacks = mCallbacksQueue.pop();
39 if (!callbacks) {
40 continue;
Alec Mouri8d7d0f42022-05-10 23:33:40 +000041 }
Patrick Williams13310b82023-05-17 14:40:18 -050042 for (auto& callback : *callbacks) {
43 callback();
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080044 }
45 }
46 });
47}
48
49BackgroundExecutor::~BackgroundExecutor() {
Alec Mouri8d7d0f42022-05-10 23:33:40 +000050 mDone = true;
51 LOG_ALWAYS_FATAL_IF(sem_post(&mSemaphore), "sem_post failed");
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080052 if (mThread.joinable()) {
53 mThread.join();
Alec Mouri8d7d0f42022-05-10 23:33:40 +000054 LOG_ALWAYS_FATAL_IF(sem_destroy(&mSemaphore), "sem_destroy failed");
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080055 }
56}
57
Alec Mouri8d7d0f42022-05-10 23:33:40 +000058void BackgroundExecutor::sendCallbacks(Callbacks&& tasks) {
Patrick Williams13310b82023-05-17 14:40:18 -050059 mCallbacksQueue.push(std::move(tasks));
Alec Mouri8d7d0f42022-05-10 23:33:40 +000060 LOG_ALWAYS_FATAL_IF(sem_post(&mSemaphore), "sem_post failed");
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080061}
62
Patrick Williams13310b82023-05-17 14:40:18 -050063} // namespace android