1 /*
2 * Copyright (c) 2021 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 "base/thread/background_task_executor.h"
17
18 #include <pthread.h>
19 #include <string>
20
21 #include "base/log/log.h"
22 #include "base/memory/memory_monitor.h"
23
24 namespace OHOS::Ace {
25 namespace {
26
27 constexpr size_t MAX_BACKGROUND_THREADS = 8;
28 constexpr uint32_t PURGE_FLAG_MASK = (1 << MAX_BACKGROUND_THREADS) - 1;
29
SetThreadName(uint32_t threadNo)30 void SetThreadName(uint32_t threadNo)
31 {
32 std::string name("ace.bg.");
33 name.append(std::to_string(threadNo));
34 #ifdef MAC_PLATFORM
35 pthread_setname_np(name.c_str());
36 #else
37 pthread_setname_np(pthread_self(), name.c_str());
38 #endif
39 }
40
41 } // namespace
42
GetInstance()43 BackgroundTaskExecutor& BackgroundTaskExecutor::GetInstance()
44 {
45 static BackgroundTaskExecutor instance;
46 return instance;
47 }
48
BackgroundTaskExecutor()49 BackgroundTaskExecutor::BackgroundTaskExecutor() : maxThreadNum_(MAX_BACKGROUND_THREADS)
50 {
51 if (maxThreadNum_ > 1) {
52 // Start other threads in the first created thread.
53 PostTask([this, num = maxThreadNum_ - 1]() { StartNewThreads(num); });
54 }
55
56 // Make sure there is at least 1 thread in background thread pool.
57 StartNewThreads(1);
58 }
59
~BackgroundTaskExecutor()60 BackgroundTaskExecutor::~BackgroundTaskExecutor()
61 {
62 std::list<std::thread> threads;
63
64 {
65 std::lock_guard<std::mutex> lock(mutex_);
66 running_ = false;
67 condition_.notify_all();
68 threads = std::move(threads_);
69 }
70
71 for (auto& threadInPool : threads) {
72 threadInPool.join();
73 }
74 }
75
PostTask(Task && task,BgTaskPriority priority)76 bool BackgroundTaskExecutor::PostTask(Task&& task, BgTaskPriority priority)
77 {
78 if (!task) {
79 return false;
80 }
81
82 std::lock_guard<std::mutex> lock(mutex_);
83 if (!running_) {
84 return false;
85 }
86 switch (priority) {
87 case BgTaskPriority::LOW:
88 lowPriorityTasks_.emplace_back(std::move(task));
89 break;
90 default:
91 tasks_.emplace_back(std::move(task));
92 break;
93 }
94 condition_.notify_one();
95 return true;
96 }
97
PostTask(const Task & task,BgTaskPriority priority)98 bool BackgroundTaskExecutor::PostTask(const Task& task, BgTaskPriority priority)
99 {
100 if (!task) {
101 return false;
102 }
103
104 std::lock_guard<std::mutex> lock(mutex_);
105 if (!running_) {
106 return false;
107 }
108 switch (priority) {
109 case BgTaskPriority::LOW:
110 lowPriorityTasks_.emplace_back(task);
111 break;
112 default:
113 tasks_.emplace_back(task);
114 break;
115 }
116 condition_.notify_one();
117 return true;
118 }
119
StartNewThreads(size_t num)120 void BackgroundTaskExecutor::StartNewThreads(size_t num)
121 {
122 uint32_t currentThreadNo = 0;
123
124 {
125 std::lock_guard<std::mutex> lock(mutex_);
126 if (!running_ || currentThreadNum_ >= maxThreadNum_) {
127 return;
128 }
129 if (currentThreadNum_ + num > maxThreadNum_) {
130 num = maxThreadNum_ - currentThreadNum_;
131 }
132 currentThreadNo = currentThreadNum_ + 1;
133 currentThreadNum_ += num;
134 }
135
136 // Start new threads.
137 std::list<std::thread> newThreads;
138 for (size_t idx = 0; idx < num; ++idx) {
139 newThreads.emplace_back(std::bind(&BackgroundTaskExecutor::ThreadLoop, this, currentThreadNo + idx));
140 }
141
142 {
143 std::lock_guard<std::mutex> lock(mutex_);
144 if (running_) {
145 threads_.splice(threads_.end(), newThreads);
146 }
147 }
148
149 for (auto& newThread : newThreads) {
150 // Join the new thread if stop running.
151 if (newThread.joinable()) {
152 newThread.join();
153 }
154 }
155 }
156
ThreadLoop(uint32_t threadNo)157 void BackgroundTaskExecutor::ThreadLoop(uint32_t threadNo)
158 {
159 LOGI("Background thread is started");
160
161 SetThreadName(threadNo);
162
163 Task task;
164 const uint32_t purgeFlag = (1 << (threadNo - 1));
165 std::unique_lock<std::mutex> lock(mutex_);
166 while (running_) {
167 if (tasks_.empty() && lowPriorityTasks_.empty()) {
168 if ((purgeFlags_ & purgeFlag) != purgeFlag) {
169 condition_.wait(lock);
170 continue;
171 }
172
173 lock.unlock();
174 LOGD("Purge malloc cache for background thread %{public}u", threadNo);
175 PurgeMallocCache();
176 lock.lock();
177 purgeFlags_ &= ~purgeFlag;
178 continue;
179 }
180 // deal with tasks_ first. do lowPriorityTasks_ only when all tasks_ done.
181 if (!tasks_.empty()) {
182 task = std::move(tasks_.front());
183 tasks_.pop_front();
184 } else {
185 task = std::move(lowPriorityTasks_.front());
186 lowPriorityTasks_.pop_front();
187 }
188
189 lock.unlock();
190 // Execute the task and clear after execution.
191 task();
192 task = nullptr;
193 lock.lock();
194 }
195
196 LOGD("Background thread is stopped");
197 }
198
TriggerGarbageCollection()199 void BackgroundTaskExecutor::TriggerGarbageCollection()
200 {
201 std::lock_guard<std::mutex> lock(mutex_);
202 purgeFlags_ = PURGE_FLAG_MASK;
203 condition_.notify_all();
204 }
205
206 } // namespace OHOS::Ace
207