• 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 #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 "ecmascript/platform/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     void SetQosPriority(bool isForeground);
49     void RecordThreadId();
50 
GetTotalThreadNum()51     uint32_t GetTotalThreadNum() const
52     {
53         return totalThreadNum_;
54     }
55 
IsInThreadPool(std::thread::id id)56     bool IsInThreadPool(std::thread::id id)
57     {
58         LockHolder holder(mtxPool_);
59         for (auto &thread : threadPool_) {
60             if (thread->get_id() == id) {
61                 return true;
62             }
63         }
64         return false;
65     }
66 
67 private:
68     void Run(uint32_t threadId);
69     void SetRunTask(uint32_t threadId, Task *task);
70 
71     std::vector<std::unique_ptr<std::thread>> threadPool_ {};
72     TaskQueue taskQueue_ {};
73     std::array<Task*, MAX_TASKPOOL_THREAD_NUM + 1> runningTask_;
74     uint32_t totalThreadNum_ {0};
75     std::vector<uint32_t> gcThreadId_ {};
76     Mutex mtx_;
77     Mutex mtxPool_;
78 };
79 }  // namespace panda::ecmascript
80 #endif  // ECMASCRIPT_TASKPOOL_RUNNER_H
81