blob: bc9087f41aded22771e6f668f472dc6d8f1d7012 [file] [log] [blame]
Yifan Hong5e2318c2016-10-27 17:19:21 -07001/*
2 * Copyright (C) 2016 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#ifndef ANDROID_TASK_RUNNER_H
17#define ANDROID_TASK_RUNNER_H
18
19#include "SynchronizedQueue.h"
20#include <thread>
21
22namespace android {
23namespace hardware {
24
25/*
26 * A background infinite loop that runs the Tasks push()'ed.
27 * Just a simple single-threaded thread pool.
28 */
29class TaskRunner {
30public:
31
32 /* Kicks off the loop immediately. */
33 TaskRunner();
34
35 /*
36 * Detaches the background thread and return immediately.
37 * Tasks in the queue will continue to be done sequentially, and _after_
38 * all tasks are done, the background thread releases the resources
39 * (the queue, the std::thread object, etc.)
40 */
41 ~TaskRunner();
42
43 /*
44 * Add a task. Return true if successful, false if
45 * the queue's size exceeds limit.
46 */
47 inline bool push(const std::function<void(void)> &t) {
48 return this->mQueue->push(t);
49 }
50
51 /*
52 * Sets the queue limit. Fails the push operation once the limit is reached.
53 */
54 inline void setLimit(size_t limit) {
55 this->mQueue->setLimit(limit);
56 }
57private:
58
59 // resources managed by the background thread.
60 bool *mRunning;
61 SynchronizedQueue<std::function<void(void)>> *mQueue;
62 std::thread *mThread;
63};
64
65} // namespace hardware
66} // namespace android
67
68#endif // ANDROID_TASK_RUNNER_H