1 /* 2 * Copyright (c) 2021-2025 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 COMMON_COMPONENTS_TASKPOOL_TASK_H 17 #define COMMON_COMPONENTS_TASKPOOL_TASK_H 18 19 #include <condition_variable> 20 #include <mutex> 21 22 #include "common_interfaces/base/common.h" 23 24 namespace common { 25 enum class TaskType : uint8_t { 26 PGO_RESET_OUT_PATH_TASK, 27 PGO_DUMP_TASK, 28 ALL, 29 }; 30 31 static constexpr int32_t ALL_TASK_ID = -1; 32 // Tasks not managed by VM 33 static constexpr int32_t GLOBAL_TASK_ID = 0; 34 35 class Task { 36 public: Task(int32_t id)37 explicit Task(int32_t id) : id_(id) {}; 38 virtual ~Task() = default; 39 virtual bool Run(uint32_t threadIndex) = 0; 40 41 NO_COPY_SEMANTIC_CC(Task); 42 NO_MOVE_SEMANTIC_CC(Task); 43 GetTaskType()44 virtual TaskType GetTaskType() const 45 { 46 return TaskType::ALL; 47 } 48 GetId()49 int32_t GetId() const 50 { 51 return id_; 52 } 53 Terminated()54 void Terminated() 55 { 56 terminate_ = true; 57 } 58 IsTerminate()59 bool IsTerminate() const 60 { 61 return terminate_; 62 } 63 64 private: 65 int32_t id_ {0}; 66 volatile bool terminate_ {false}; 67 }; 68 69 class TaskPackMonitor { 70 public: TaskPackMonitor(int running,int maxRunning)71 explicit TaskPackMonitor(int running, int maxRunning) : running_(running), maxRunning_(maxRunning) 72 { 73 DCHECK_CC(running_ >= 0); 74 DCHECK_CC(running_ <= maxRunning_); 75 } 76 ~TaskPackMonitor() = default; 77 WaitAllFinished()78 void WaitAllFinished() 79 { 80 std::unique_lock<std::mutex> lock(mutex_); 81 while (running_ > 0) { 82 cv_.wait(lock); 83 } 84 } 85 TryAddNewOne()86 bool TryAddNewOne() 87 { 88 std::lock_guard<std::mutex> guard(mutex_); 89 DCHECK_CC(running_ >= 0); 90 if (running_ < maxRunning_) { 91 ++running_; 92 return true; 93 } 94 return false; 95 } 96 NotifyFinishOne()97 void NotifyFinishOne() 98 { 99 std::lock_guard<std::mutex> guard(mutex_); 100 if (--running_ == 0) { 101 cv_.notify_all(); 102 } 103 } 104 105 NO_COPY_SEMANTIC_CC(TaskPackMonitor); 106 NO_MOVE_SEMANTIC_CC(TaskPackMonitor); 107 private: 108 int running_ {0}; 109 int maxRunning_ {0}; 110 std::condition_variable cv_; 111 std::mutex mutex_; 112 }; 113 } // namespace common 114 #endif // COMMON_COMPONENTS_TASKPOOL_TASK_H 115