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 #ifndef ECMASCRIPT_TASKPOOL_RUNNER_H 17 #define ECMASCRIPT_TASKPOOL_RUNNER_H 18 19 #include <array> 20 #include <memory> 21 #include <thread> 22 #include <vector> 23 24 #include "ecmascript/common.h" 25 #include "ecmascript/taskpool/task_queue.h" 26 #include "libpandabase/os/mutex.h" 27 28 namespace panda::ecmascript { 29 static constexpr uint32_t MIN_TASKPOOL_THREAD_NUM = 3; 30 static constexpr uint32_t MAX_TASKPOOL_THREAD_NUM = 7; 31 static constexpr uint32_t DEFAULT_TASKPOOL_THREAD_NUM = 0; 32 33 class Runner { 34 public: 35 explicit Runner(uint32_t threadNum); 36 ~Runner() = default; 37 38 NO_COPY_SEMANTIC(Runner); 39 NO_MOVE_SEMANTIC(Runner); 40 PostTask(std::unique_ptr<Task> task)41 void PostTask(std::unique_ptr<Task> task) 42 { 43 taskQueue_.PostTask(std::move(task)); 44 } 45 46 void PUBLIC_API TerminateThread(); 47 void TerminateTask(int32_t id, TaskType type); 48 GetTotalThreadNum()49 uint32_t GetTotalThreadNum() const 50 { 51 return totalThreadNum_; 52 } 53 IsInThreadPool(std::thread::id id)54 bool IsInThreadPool(std::thread::id id) 55 { 56 os::memory::LockHolder holder(mtxPool_); 57 for (auto &thread : threadPool_) { 58 if (thread->get_id() == id) { 59 return true; 60 } 61 } 62 return false; 63 } 64 65 private: 66 void Run(uint32_t threadId); 67 void SetRunTask(uint32_t threadId, Task *task); 68 69 std::vector<std::unique_ptr<std::thread>> threadPool_ {}; 70 TaskQueue taskQueue_ {}; 71 std::array<Task*, MAX_TASKPOOL_THREAD_NUM + 1> runningTask_; 72 uint32_t totalThreadNum_ {0}; 73 os::memory::Mutex mtx_; 74 os::memory::Mutex mtxPool_; 75 }; 76 } // namespace panda::ecmascript 77 #endif // ECMASCRIPT_TASKPOOL_RUNNER_H 78