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 20namespace panda::ecmascript { 21Taskpool *Taskpool::GetCurrentTaskpool() 22{ 23 static Taskpool *taskpool = new Taskpool(); 24 return taskpool; 25} 26 27void Taskpool::Initialize(int threadNum, 28 std::function<void(os::thread::native_handle_type)> prologueHook, 29 const std::function<void(os::thread::native_handle_type)> epilogueHook) 30{ 31 LockHolder lock(mutex_); 32 if (isInitialized_++ <= 0) { 33 runner_ = std::make_unique<Runner>(TheMostSuitableThreadNum(threadNum), prologueHook, epilogueHook); 34 } 35} 36 37void Taskpool::Destroy(int32_t id) 38{ 39 ASSERT(id != 0); 40 LockHolder lock(mutex_); 41 if (isInitialized_ <= 0) { 42 return; 43 } 44 isInitialized_--; 45 if (isInitialized_ == 0) { 46 runner_->TerminateThread(); 47 } else { 48 runner_->TerminateTask(id, TaskType::ALL); 49 } 50} 51 52void Taskpool::TerminateTask(int32_t id, TaskType type) 53{ 54 if (isInitialized_ <= 0) { 55 return; 56 } 57 runner_->TerminateTask(id, type); 58} 59 60uint32_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 if (numOfThreads > MIN_TASKPOOL_THREAD_NUM) { 67 return numOfThreads - 1; // 1 for daemon thread. 68 } 69 return MIN_TASKPOOL_THREAD_NUM; // At least MIN_TASKPOOL_THREAD_NUM GC threads, and 1 extra daemon thread. 70} 71 72void Taskpool::ForEachTask(const std::function<void(Task*)> &f) 73{ 74 if (isInitialized_ <= 0) { 75 return; 76 } 77 runner_->ForEachTask(f); 78} 79} // namespace panda::ecmascript 80