1 /*
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_HIDL_TASK_RUNNER_H
17 #define ANDROID_HIDL_TASK_RUNNER_H
18 
19 #include <functional>
20 #include <memory>
21 #include <thread>
22 
23 namespace android {
24 namespace hardware {
25 namespace details {
26 
27 using Task = std::function<void(void)>;
28 
29 template <typename T>
30 struct SynchronizedQueue;
31 
32 /*
33  * A background infinite loop that runs the Tasks push()'ed.
34  * Equivalent to a simple single-threaded Looper.
35  */
36 class TaskRunner {
37 public:
38 
39     /* Create an empty task runner. Nothing will be done until start() is called. */
40     TaskRunner();
41 
42     /*
43      * Notify the background thread to terminate and return immediately.
44      * Tasks in the queue will continue to be done sequentially in background
45      * until all tasks are finished.
46      */
47     ~TaskRunner();
48 
49     /*
50      * Sets the queue limit. Fails the push operation once the limit is reached.
51      * This function is named start for legacy reasons and to maintain ABI
52      * stability, but the underlying thread running tasks isn't started until
53      * the first task is pushed.
54      */
55     void start(size_t limit);
56 
57     /*
58      * Add a task. Return true if successful, false if
59      * the queue's size exceeds limit or t doesn't contain a callable target.
60      */
61     bool push(const Task &t);
62 
63 private:
64     std::shared_ptr<SynchronizedQueue<Task>> mQueue;
65 };
66 
67 } // namespace details
68 } // namespace hardware
69 } // namespace android
70 
71 #endif // ANDROID_HIDL_TASK_RUNNER_H
72