1 /*
2  * Copyright (c) 2023 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 FFRT_TASK_MANAGER_H
17 #define FFRT_TASK_MANAGER_H
18 
19 #include <array>
20 #include <atomic>
21 
22 #include "tm/cpu_task.h"
23 
24 namespace ffrt {
25 class TaskManager {
26 public:
Instance()27     static TaskManager& Instance()
28     {
29         static TaskManager manager;
30         return manager;
31     }
32 
GetCount(TaskState::State state)33     uint64_t GetCount(TaskState::State state) const
34     {
35         return taskCount[static_cast<size_t>(state)];
36     }
37 
38     void TaskStateCount(CPUEUTask* task);
39 
40 private:
41     TaskManager() = default;
42 
IncreCount(std::atomic_uint64_t & count)43     void IncreCount(std::atomic_uint64_t& count)
44     {
45         count.fetch_add(1, std::memory_order_relaxed);
46     }
47 
DecreCount(std::atomic_uint64_t & count)48     void DecreCount(std::atomic_uint64_t& count)
49     {
50         while (true) {
51             auto old = count.load();
52             if (old <= 0) {
53                 break;
54             }
55 
56             if (count.compare_exchange_weak(old, old - 1, std::memory_order_relaxed)) {
57                 break;
58             }
59         }
60     }
61 
62     inline void CalcTaskTime(CPUEUTask* task);
63 
64     std::array<std::atomic_uint64_t, static_cast<size_t>(TaskState::MAX)> taskCount;
65 
66     std::atomic_uint64_t maxWaitingTime;
67     std::atomic<double> avgWaitingTime;
68 
69     std::atomic_uint64_t maxRunningTime;
70     std::atomic<double> avgRunningTime;
71 };
72 } // namespace ffrt
73 
74 #endif