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