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