• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 #ifndef HIVIEW_EVENT_LOGGER_EVENT_THREAD_POOL_H
16 #define HIVIEW_EVENT_LOGGER_EVENT_THREAD_POOL_H
17 #include <atomic>
18 #include <cstdint>
19 #include <mutex>
20 #include <string>
21 #include <thread>
22 #include <vector>
23 
24 #include "event_priority_queue.h"
25 #include "nocopyable.h"
26 #include "time_util.h"
27 
28 namespace OHOS {
29 namespace HiviewDFX {
30 class TaskEvent {
31 public:
TaskEvent(uint8_t priority,uint64_t targetTime,Task task,const std::string & name)32     TaskEvent(uint8_t priority, uint64_t targetTime, Task task, const std::string &name)
33         : priority_(priority), targetTime_(targetTime), task_(task), name_(name)
34     {
35         seq = TimeUtil::GetNanoTime();
36     }
37 
~TaskEvent()38     ~TaskEvent() {}
39     uint8_t priority_;
40     uint64_t targetTime_;
41     Task task_;
42     std::string name_;
43     uint64_t seq;
44 
45     bool operator<(const TaskEvent &obj) const
46     {
47         if (this->targetTime_ > obj.targetTime_) {
48             return true;
49         } else if (this->targetTime_ == obj.targetTime_) {
50             if (this->priority_ > obj.priority_) {
51                 return true;
52             }
53         }
54         return false;
55     }
56 };
57 
58 
59 class EventThreadPool {
60 public:
61     DISALLOW_COPY_AND_MOVE(EventThreadPool);
62     EventThreadPool(int maxCout, const std::string& name);
63     ~EventThreadPool();
64 
65     enum Priority {
66         HIGHEST_PRIORITY = 1,
67         HIGH_PRIORITY = 10,
68         LOW_PRIORITY = 20,
69         LOWEST_PRIORITY = 30,
70         IDLE_PRIORITY = 50,
71     };
72 
73     void Start();
74     void Stop();
75     void AddTask(Task task, const std::string &name,
76         uint64_t delay = 0, uint8_t priority = Priority::IDLE_PRIORITY);
77 
78 private:
79     int maxCout_;
80     std::string name_;
81     std::atomic<bool> runing_;
82     std::vector<std::thread> pool_;
83     std::mutex mutex_;
84     std::condition_variable cvSync_;
85     EventPriorityQueue<TaskEvent> taskQueue_;
86 
87     TaskEvent ObtainTask(uint64_t &targetTime);
88     void TaskCallback();
89 };
90 }  // namespace HiviewDFX
91 }  // namespace OHOS
92 #endif  // HIVIEW_EVENT_LOGGER_EVENT_THREAD_POOL_H