1 /* 2 * Copyright (C) 2020 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 17 #ifndef FRAMEWORK_NATIVE_CMD_TASKQUEUE_H_ 18 #define FRAMEWORK_NATIVE_CMD_TASKQUEUE_H_ 19 20 #include <mutex> 21 #include <queue> 22 23 #include <android-base/macros.h> 24 25 namespace android { 26 namespace os { 27 namespace dumpstate { 28 29 /* 30 * A task queue for dumpstate to collect tasks such as adding file to the zip 31 * which are needed to run in a single thread. The task is a callable function 32 * included a cancel task boolean parameter. The TaskQueue could 33 * cancel the task in the destructor if the task has never been called. 34 */ 35 class TaskQueue { 36 public: 37 TaskQueue() = default; 38 ~TaskQueue(); 39 40 /* 41 * Adds a task into the queue. 42 * 43 * |f| Callable function to execute the task. The function must include a 44 * boolean parameter for TaskQueue to notify whether the task is 45 * cancelled or not. 46 * |args| A list of arguments. 47 */ add(F && f,Args &&...args)48 template<class F, class... Args> void add(F&& f, Args&&... args) { 49 auto func = std::bind(std::forward<F>(f), std::forward<Args>(args)...); 50 std::unique_lock lock(lock_); 51 tasks_.emplace([=](bool cancelled) { 52 std::invoke(func, cancelled); 53 }); 54 } 55 56 /* 57 * Invokes all tasks in the task queue. 58 * 59 * |do_cancel| true to cancel all tasks in the queue. 60 */ 61 void run(bool do_cancel); 62 63 private: 64 using Task = std::function<void(bool)>; 65 66 std::mutex lock_; 67 std::queue<Task> tasks_; 68 69 DISALLOW_COPY_AND_ASSIGN(TaskQueue); 70 }; 71 72 } // namespace dumpstate 73 } // namespace os 74 } // namespace android 75 76 #endif //FRAMEWORK_NATIVE_CMD_TASKQUEUE_H_ 77