2 * Copyright (C) 2012 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 // #define LOG_NDEBUG 0
18 #define LOG_TAG "WorkQueue"
20 #include <utils/Log.h>
21 #include "WorkQueue.h"
27 WorkQueue::WorkQueue(size_t maxThreads, bool canCallJava) :
28 mMaxThreads(maxThreads), mCanCallJava(canCallJava),
29 mCanceled(false), mFinished(false), mIdleThreads(0) {
32 WorkQueue::~WorkQueue() {
38 status_t WorkQueue::schedule(WorkUnit* workUnit, size_t backlog) {
41 if (mFinished || mCanceled) {
42 return INVALID_OPERATION;
45 if (mWorkThreads.size() < mMaxThreads
46 && mIdleThreads < mWorkUnits.size() + 1) {
47 sp<WorkThread> workThread = new WorkThread(this, mCanCallJava);
48 status_t status = workThread->run("WorkQueue::WorkThread");
52 mWorkThreads.add(workThread);
55 while (mWorkUnits.size() >= mMaxThreads * backlog) {
56 mWorkDequeuedCondition.wait(mLock);
57 if (mFinished || mCanceled) {
58 return INVALID_OPERATION;
63 mWorkUnits.add(workUnit);
64 mWorkChangedCondition.broadcast();
68 status_t WorkQueue::cancel() {
71 return cancelLocked();
74 status_t WorkQueue::cancelLocked() {
76 return INVALID_OPERATION;
82 size_t count = mWorkUnits.size();
83 for (size_t i = 0; i < count; i++) {
84 delete mWorkUnits.itemAt(i);
87 mWorkChangedCondition.broadcast();
88 mWorkDequeuedCondition.broadcast();
93 status_t WorkQueue::finish() {
98 return INVALID_OPERATION;
102 mWorkChangedCondition.broadcast();
105 // It is not possible for the list of work threads to change once the mFinished
106 // flag has been set, so we can access mWorkThreads outside of the lock here.
107 size_t count = mWorkThreads.size();
108 for (size_t i = 0; i < count; i++) {
109 mWorkThreads.itemAt(i)->join();
111 mWorkThreads.clear();
115 bool WorkQueue::threadLoop() {
125 if (!mWorkUnits.isEmpty()) {
126 workUnit = mWorkUnits.itemAt(0);
127 mWorkUnits.removeAt(0);
129 mWorkDequeuedCondition.broadcast();
137 mWorkChangedCondition.wait(mLock);
141 bool shouldContinue = workUnit->run();
149 if (!shouldContinue) {
158 // --- WorkQueue::WorkThread ---
160 WorkQueue::WorkThread::WorkThread(WorkQueue* workQueue, bool canCallJava) :
161 Thread(canCallJava), mWorkQueue(workQueue) {
164 WorkQueue::WorkThread::~WorkThread() {
167 bool WorkQueue::WorkThread::threadLoop() {
168 return mWorkQueue->threadLoop();
171 }; // namespace android