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 "ecmascript/taskpool/taskpool.h"
17
18 #include "ecmascript/platform/os.h"
19
20 namespace panda::ecmascript {
GetCurrentTaskpool()21 Taskpool *Taskpool::GetCurrentTaskpool()
22 {
23 static Taskpool *taskpool = new Taskpool();
24 return taskpool;
25 }
26
Initialize(int threadNum)27 void Taskpool::Initialize(int threadNum)
28 {
29 LockHolder lock(mutex_);
30 if (isInitialized_++ <= 0) {
31 runner_ = std::make_unique<Runner>(TheMostSuitableThreadNum(threadNum));
32 }
33 }
34
Destroy(int32_t id)35 void Taskpool::Destroy(int32_t id)
36 {
37 LockHolder lock(mutex_);
38 if (isInitialized_ <= 0) {
39 return;
40 }
41 isInitialized_--;
42 if (isInitialized_ == 0) {
43 runner_->TerminateThread();
44 } else {
45 runner_->TerminateTask(id, TaskType::ALL);
46 }
47 }
48
TerminateTask(int32_t id,TaskType type)49 void Taskpool::TerminateTask(int32_t id, TaskType type)
50 {
51 if (isInitialized_ <= 0) {
52 return;
53 }
54 runner_->TerminateTask(id, type);
55 }
56
TheMostSuitableThreadNum(uint32_t threadNum) const57 uint32_t Taskpool::TheMostSuitableThreadNum(uint32_t threadNum) const
58 {
59 if (threadNum > 0) {
60 return std::min<uint32_t>(threadNum, MAX_TASKPOOL_THREAD_NUM);
61 }
62 uint32_t numOfThreads = std::min<uint32_t>(NumberOfCpuCore() / 2, MAX_TASKPOOL_THREAD_NUM);
63 return std::max<uint32_t>(numOfThreads, MIN_TASKPOOL_THREAD_NUM);
64 }
65 } // namespace panda::ecmascript
66