1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef PANDA_LIBPANDABASE_TASKMANAGER_WORKER_THREAD_H 17 #define PANDA_LIBPANDABASE_TASKMANAGER_WORKER_THREAD_H 18 19 #include "libpandabase/taskmanager/task.h" 20 #include <thread> 21 #include <queue> 22 #include <unordered_map> 23 24 namespace panda::taskmanager { 25 26 using TaskPropertiesCounterMap = std::unordered_map<TaskProperties, size_t, TaskProperties::Hash>; 27 28 class TaskScheduler; 29 30 class WorkerThread { 31 public: 32 NO_COPY_SEMANTIC(WorkerThread); 33 NO_MOVE_SEMANTIC(WorkerThread); 34 35 /** 36 * FinishedTasksCallback instance should be called after tasks finishing. As argument you should input count of 37 * finished tasks. 38 */ 39 using FinishedTasksCallback = std::function<void(TaskPropertiesCounterMap)>; 40 41 static constexpr size_t WORKER_QUEUE_SIZE = 4; 42 43 explicit WorkerThread(FinishedTasksCallback callback, size_t tasksCount = WORKER_QUEUE_SIZE); 44 ~WorkerThread(); 45 46 /** 47 * @brief Adds task in internal queues. 48 * @param task - task that will be added in internal queues 49 */ 50 void AddTask(Task &&task); 51 52 /// @brief Waits for worker finish 53 void Join(); 54 55 /// @brief Returns true if all internal queues are empty 56 bool IsEmpty() const; 57 58 private: 59 [[nodiscard]] Task PopTask(); 60 61 void WorkerLoop(size_t tasksCount); 62 63 void ExecuteTasks(); 64 65 std::thread *thread_; 66 67 std::queue<Task> backgroundQueue_; 68 std::queue<Task> foregroundQueue_; 69 70 size_t size_ {0}; 71 72 TaskPropertiesCounterMap finishedTasksCounterMap_; 73 74 FinishedTasksCallback finishedTasksCallback_; 75 }; 76 77 } // namespace panda::taskmanager 78 79 #endif // PANDA_LIBPANDABASE_TASKMANAGER_WORKER_THREAD_H 80