• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     os::memory::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     os::memory::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     {
52         os::memory::LockHolder lock(mutex_);
53         if (isInitialized_ <= 0) {
54             return;
55         }
56     }
57     runner_->TerminateTask(id, type);
58 }
59 
TheMostSuitableThreadNum(uint32_t threadNum) const60 uint32_t Taskpool::TheMostSuitableThreadNum(uint32_t threadNum) const
61 {
62     if (threadNum > 0) {
63         return std::min<uint32_t>(threadNum, MAX_TASKPOOL_THREAD_NUM);
64     }
65     uint32_t numOfThreads = std::min<uint32_t>(NumberOfCpuCore() / 2, MAX_TASKPOOL_THREAD_NUM);
66     return std::max<uint32_t>(numOfThreads, MIN_TASKPOOL_THREAD_NUM);
67 }
68 }  // namespace panda::ecmascript
69