• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 
16 #ifndef RELIABILITY_WATCHDOG_INNER_H
17 #define RELIABILITY_WATCHDOG_INNER_H
18 
19 #include <atomic>
20 #include <condition_variable>
21 #include <memory>
22 #include <mutex>
23 #include <queue>
24 #include <set>
25 #include <string>
26 #include <thread>
27 
28 #include "watchdog_task.h"
29 #include "singleton.h"
30 
31 namespace OHOS {
32 namespace HiviewDFX {
33 class WatchdogInner : public Singleton<WatchdogInner> {
34     DECLARE_SINGLETON(WatchdogInner);
35 public:
36     int AddThread(const std::string &name, std::shared_ptr<AppExecFwk::EventHandler> handler, uint64_t interval);
37     int AddThread(const std::string &name, std::shared_ptr<AppExecFwk::EventHandler> handler,
38         TimeOutCallback timeOutCallback, uint64_t interval);
39     void RunOneShotTask(const std::string& name, Task&& task, uint64_t delay);
40     void RunPeriodicalTask(const std::string& name, Task&& task, uint64_t interval, uint64_t delay);
41     void StopWatchdog();
42 
43 private:
44     bool Start();
45     bool Stop();
46     bool IsTaskExistLocked(const std::string& name);
47     bool IsExceedMaxTaskLocked();
48     bool InsertWatchdogTaskLocked(const std::string& name, WatchdogTask&& task);
49     uint64_t FetchNextTask(uint64_t now, WatchdogTask& task);
50     void ReInsertTaskIfNeed(WatchdogTask& task);
51     void CreateWatchdogThreadIfNeed();
52 
53     static const unsigned int MAX_WATCH_NUM = 128; // 128: max handler thread
54     std::priority_queue<WatchdogTask> checkerQueue_; // protected by lock_
55     std::unique_ptr<std::thread> threadLoop_;
56     std::mutex lock_;
57     std::condition_variable condition_;
58     std::atomic_bool isNeedStop_ = false;
59     std::once_flag flag_;
60     std::set<std::string> taskNameSet_;
61 };
62 } // end of namespace HiviewDFX
63 } // end of namespace OHOS
64 #endif
65