blob: a15de2b1839e7658c0cacf9f979700b31bbc6bd0 [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>() {
31 mThread = std::thread([&]() {
Alec Mouri8d7d0f42022-05-10 23:33:40 +000032 LOG_ALWAYS_FATAL_IF(sem_init(&mSemaphore, 0, 0), "sem_init failed");
33 while (!mDone) {
34 LOG_ALWAYS_FATAL_IF(sem_wait(&mSemaphore), "sem_wait failed (%d)", errno);
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080035
Alec Mouri8d7d0f42022-05-10 23:33:40 +000036 ftl::SmallVector<Work*, 10> workItems;
37
38 Work* work = mWorks.pop();
39 while (work) {
40 workItems.push_back(work);
41 work = mWorks.pop();
42 }
43
44 // Sequence numbers are guaranteed to be in intended order, as we assume a single
45 // producer and single consumer.
46 std::stable_sort(workItems.begin(), workItems.end(), [](Work* left, Work* right) {
47 return left->sequence < right->sequence;
48 });
49 for (Work* work : workItems) {
50 for (auto& task : work->tasks) {
51 task();
52 }
53 delete work;
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080054 }
55 }
56 });
57}
58
59BackgroundExecutor::~BackgroundExecutor() {
Alec Mouri8d7d0f42022-05-10 23:33:40 +000060 mDone = true;
61 LOG_ALWAYS_FATAL_IF(sem_post(&mSemaphore), "sem_post failed");
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080062 if (mThread.joinable()) {
63 mThread.join();
Alec Mouri8d7d0f42022-05-10 23:33:40 +000064 LOG_ALWAYS_FATAL_IF(sem_destroy(&mSemaphore), "sem_destroy failed");
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080065 }
66}
67
Alec Mouri8d7d0f42022-05-10 23:33:40 +000068void BackgroundExecutor::sendCallbacks(Callbacks&& tasks) {
69 Work* work = new Work();
70 work->sequence = mSequence;
71 work->tasks = std::move(tasks);
72 mWorks.push(work);
73 mSequence++;
74 LOG_ALWAYS_FATAL_IF(sem_post(&mSemaphore), "sem_post failed");
Vishnu Nair34eb9ca2021-11-18 15:23:23 -080075}
76
77} // namespace android