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/runner.h"
17
18 #include "libpandabase/os/mutex.h"
19 #include "libpandabase/os/thread.h"
20
21 namespace panda::ecmascript {
Runner(uint32_t threadNum)22 Runner::Runner(uint32_t threadNum) : totalThreadNum_(threadNum)
23 {
24 for (uint32_t i = 0; i < threadNum; i++) {
25 // main thread is 0;
26 std::unique_ptr<std::thread> thread = std::make_unique<std::thread>(&Runner::Run, this, i + 1);
27 threadPool_.emplace_back(std::move(thread));
28 }
29
30 for (uint32_t i = 0; i < runningTask_.size(); i++) {
31 runningTask_[i] = nullptr;
32 }
33 }
34
TerminateTask(int32_t id,TaskType type)35 void Runner::TerminateTask(int32_t id, TaskType type)
36 {
37 taskQueue_.TerminateTask(id, type);
38 os::memory::LockHolder holder(mtx_);
39 for (uint32_t i = 0; i < runningTask_.size(); i++) {
40 if (runningTask_[i] != nullptr) {
41 if (id != ALL_TASK_ID && id != runningTask_[i]->GetId()) {
42 continue;
43 }
44 if (type != TaskType::ALL && type != runningTask_[i]->GetTaskType()) {
45 continue;
46 }
47 runningTask_[i]->Terminated();
48 }
49 }
50 }
51
TerminateThread()52 void Runner::TerminateThread()
53 {
54 TerminateTask(ALL_TASK_ID, TaskType::ALL);
55 taskQueue_.Terminate();
56
57 os::memory::LockHolder holder(mtxPool_);
58 uint32_t threadNum = threadPool_.size();
59 for (uint32_t i = 0; i < threadNum; i++) {
60 threadPool_.at(i)->join();
61 }
62 threadPool_.clear();
63 }
64
SetRunTask(uint32_t threadId,Task * task)65 void Runner::SetRunTask(uint32_t threadId, Task *task)
66 {
67 os::memory::LockHolder holder(mtx_);
68 runningTask_[threadId] = task;
69 }
70
Run(uint32_t threadId)71 void Runner::Run(uint32_t threadId)
72 {
73 os::thread::native_handle_type thread = os::thread::GetNativeHandle();
74 os::thread::SetThreadName(thread, "GC_WorkerThread");
75 while (std::unique_ptr<Task> task = taskQueue_.PopTask()) {
76 SetRunTask(threadId, task.get());
77 task->Run(threadId);
78 SetRunTask(threadId, nullptr);
79 }
80 }
81 } // namespace panda::ecmascript
82