• 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_TASKPOOL_H
17 #define ECMASCRIPT_TASKPOOL_TASKPOOL_H
18 
19 #include <memory>
20 
21 #include "ecmascript/common.h"
22 #include "ecmascript/taskpool/runner.h"
23 #include "ecmascript/platform/mutex.h"
24 
25 namespace panda::ecmascript {
26 class Taskpool {
27 public:
28     PUBLIC_API static Taskpool *GetCurrentTaskpool();
29 
30     Taskpool() = default;
~Taskpool()31     PUBLIC_API ~Taskpool()
32     {
33         LockHolder lock(mutex_);
34         runner_->TerminateThread();
35         isInitialized_ = 0;
36     }
37 
38     NO_COPY_SEMANTIC(Taskpool);
39     NO_MOVE_SEMANTIC(Taskpool);
40 
41     void Initialize(int threadNum = DEFAULT_TASKPOOL_THREAD_NUM);
42     void Destroy(int32_t id);
43 
PostTask(std::unique_ptr<Task> task)44     void PostTask(std::unique_ptr<Task> task) const
45     {
46         if (isInitialized_ > 0) {
47             runner_->PostTask(std::move(task));
48         }
49     }
50 
51     // Terminate a task of a specified type
52     void TerminateTask(int32_t id, TaskType type = TaskType::ALL);
53 
GetTotalThreadNum()54     uint32_t GetTotalThreadNum() const
55     {
56         return runner_->GetTotalThreadNum();
57     }
58 
IsInThreadPool(std::thread::id id)59     bool IsInThreadPool(std::thread::id id) const
60     {
61         return runner_->IsInThreadPool(id);
62     }
63 
SetThreadPriority(bool isForeground)64     void SetThreadPriority(bool isForeground)
65     {
66         runner_->SetQosPriority(isForeground);
67     }
68 
69 private:
70     uint32_t TheMostSuitableThreadNum(uint32_t threadNum) const;
71 
72     std::unique_ptr<Runner> runner_;
73     volatile int isInitialized_ = 0;
74     Mutex mutex_;
75 };
76 }  // namespace panda::ecmascript
77 #endif  // ECMASCRIPT_PALTFORM_PLATFORM_H
78