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_TASKPOOL_H 17 #define COMMON_COMPONENTS_TASKPOOL_TASKPOOL_H 18 19 #include <memory> 20 #include <mutex> 21 22 #include "common_components/taskpool/runner.h" 23 #include "common_interfaces/base/common.h" 24 25 namespace common { 26 class PUBLIC_API Taskpool { 27 public: 28 PUBLIC_API static Taskpool *GetCurrentTaskpool(); 29 30 Taskpool() = default; ~Taskpool()31 PUBLIC_API ~Taskpool() 32 { 33 std::lock_guard<std::mutex> guard(mutex_); 34 runner_->TerminateThread(); 35 isInitialized_ = 0; 36 } 37 38 NO_COPY_SEMANTIC_CC(Taskpool); 39 NO_MOVE_SEMANTIC_CC(Taskpool); 40 41 void Initialize(int threadNum = DEFAULT_TASKPOOL_THREAD_NUM, 42 std::function<void(native_handle_type)> prologueHook = nullptr, 43 const std::function<void(native_handle_type)> epilogueHook = nullptr); 44 void Destroy(int32_t id); 45 PostTask(std::unique_ptr<Task> task)46 void PostTask(std::unique_ptr<Task> task) const 47 { 48 DCHECK_CC(isInitialized_ > 0); 49 if (isInitialized_ > 0) { 50 runner_->PostTask(std::move(task)); 51 } 52 } 53 PostDelayedTask(std::unique_ptr<Task> task,uint64_t delayMilliseconds)54 void PostDelayedTask(std::unique_ptr<Task> task, uint64_t delayMilliseconds) const 55 { 56 DCHECK_CC(isInitialized_ > 0); 57 if (isInitialized_ > 0) { 58 runner_->PostDelayedTask(std::move(task), delayMilliseconds); 59 } 60 } 61 62 // Terminate a task of a specified type 63 void TerminateTask(int32_t id, TaskType type = TaskType::ALL); 64 GetTotalThreadNum()65 uint32_t GetTotalThreadNum() const 66 { 67 return runner_->GetTotalThreadNum(); 68 } 69 IsInThreadPool(std::thread::id id)70 bool IsInThreadPool(std::thread::id id) const 71 { 72 return runner_->IsInThreadPool(id); 73 } 74 SetThreadPriority(PriorityMode mode)75 void SetThreadPriority(PriorityMode mode) 76 { 77 runner_->SetQosPriority(mode); 78 } 79 80 void ForEachTask(const std::function<void(Task*)> &f); 81 82 private: 83 virtual uint32_t TheMostSuitableThreadNum(uint32_t threadNum) const; 84 85 std::unique_ptr<Runner> runner_; 86 volatile int isInitialized_ = 0; 87 std::mutex mutex_; 88 }; 89 } // namespace common 90 #endif // COMMON_COMPONENTS_TASKPOOL_TASKPOOL_H 91