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