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 #include "common_components/taskpool/taskpool.h"
17
18 #include "common_components/platform/cpu.h"
19
20 namespace common {
GetCurrentTaskpool()21 Taskpool *Taskpool::GetCurrentTaskpool()
22 {
23 static Taskpool *taskpool = new Taskpool();
24 return taskpool;
25 }
26
Initialize(int threadNum,std::function<void (native_handle_type)> prologueHook,const std::function<void (native_handle_type)> epilogueHook)27 void Taskpool::Initialize(int threadNum,
28 std::function<void(native_handle_type)> prologueHook,
29 const std::function<void(native_handle_type)> epilogueHook)
30 {
31 std::lock_guard<std::mutex> guard(mutex_);
32 if (isInitialized_++ <= 0) {
33 runner_ = std::make_unique<Runner>(TheMostSuitableThreadNum(threadNum), prologueHook, epilogueHook);
34 }
35 }
36
Destroy(int32_t id)37 void Taskpool::Destroy(int32_t id)
38 {
39 std::lock_guard<std::mutex> guard(mutex_);
40 if (isInitialized_ <= 0) {
41 return;
42 }
43 isInitialized_--;
44 if (isInitialized_ == 0) {
45 runner_->TerminateThread();
46 } else {
47 runner_->TerminateTask(id, TaskType::ALL);
48 }
49 }
50
TerminateTask(int32_t id,TaskType type)51 void Taskpool::TerminateTask(int32_t id, TaskType type)
52 {
53 if (isInitialized_ <= 0) {
54 return;
55 }
56 runner_->TerminateTask(id, type);
57 }
58
TheMostSuitableThreadNum(uint32_t threadNum) const59 uint32_t Taskpool::TheMostSuitableThreadNum(uint32_t threadNum) const
60 {
61 if (threadNum > 0) {
62 return std::min<uint32_t>(threadNum, MAX_TASKPOOL_THREAD_NUM);
63 }
64 uint32_t numOfThreads = std::min<uint32_t>(NumberOfCpuCore() / 2, MAX_TASKPOOL_THREAD_NUM);
65 if (numOfThreads > MIN_TASKPOOL_THREAD_NUM) {
66 return numOfThreads - 1; // 1 for daemon thread.
67 }
68 return MIN_TASKPOOL_THREAD_NUM; // At least MIN_TASKPOOL_THREAD_NUM GC threads, and 1 extra daemon thread.
69 }
70
ForEachTask(const std::function<void (Task *)> & f)71 void Taskpool::ForEachTask(const std::function<void(Task*)> &f)
72 {
73 if (isInitialized_ <= 0) {
74 return;
75 }
76 runner_->ForEachTask(f);
77 }
78 } // namespace common
79