blob: 39a0afa1899366200f163358d0d907ca2fedc5f6 [file]
/*
* Copyright (C) 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "AsyncWorker.h"
AsyncWorker::AsyncWorker() : mState(std::make_shared<AsyncWorkerState>()) {}
AsyncWorker::~AsyncWorker() {
signalWorkerDone();
if (mThread.joinable()) {
mThread.join();
}
}
void AsyncWorker::post(std::function<void()> runnable) {
std::scoped_lock<std::mutex> lock(mState->mMutex);
// Not joinable means mThread is still default constructed
// and needs initialization now.
if (!mThread.joinable()) {
mThread = std::thread(&AsyncWorker::run, mState);
}
mState->mRunnables.emplace_back(std::move(runnable));
mState->mCv.notify_one();
}
bool AsyncWorker::AsyncWorkerState::waitingDone() {
return mDone || !mRunnables.empty();
}
void AsyncWorker::run(std::shared_ptr<AsyncWorkerState> state) {
std::unique_lock<std::mutex> lock(state->mMutex);
android::base::ScopedLockAssertion lock_assertion(state->mMutex);
while (!state->mDone) {
while (!state->mRunnables.empty()) {
std::deque<std::function<void()>> runnables = std::move(state->mRunnables);
state->mRunnables.clear();
lock.unlock();
// Run outside the lock since the runnable might trigger another
// post to the async worker.
execute(runnables);
lock.lock();
}
state->mCv.wait(lock, [&state] {
android::base::ScopedLockAssertion lock_assertion(state->mMutex);
return state->waitingDone();
});
}
}
void AsyncWorker::execute(std::deque<std::function<void()>>& runnables) {
while (!runnables.empty()) {
std::function<void()> runnable = runnables.front();
runnables.pop_front();
runnable();
}
}
void AsyncWorker::signalWorkerDone() {
std::scoped_lock<std::mutex> lock(mState->mMutex);
mState->mDone = true;
mState->mCv.notify_all();
}
void AsyncWorker::exitNoFlush() {
signalWorkerDone();
if (mThread.joinable()) {
mThread.detach();
}
}