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 WATCHDOG_H 17 #define WATCHDOG_H 18 19 #include <atomic> 20 #include <condition_variable> 21 #include <thread> 22 #include "media_dfx.h" 23 #include "media_log.h" 24 25 namespace OHOS { 26 namespace Media { 27 /** 28 * More than timeoutMs_ If Notify() is not used to trigger the dog feeding action within, the Alarm() action 29 * will be triggered. When notify() is restored, the AlarmRecovery() action will be triggered. 30 * See interface details for specific usage. 31 */ 32 class __attribute__((visibility("default"))) WatchDog { 33 public: 34 WatchDog() = default; WatchDog(uint32_t timeoutMs)35 explicit WatchDog(uint32_t timeoutMs) : timeoutMs_(timeoutMs) {}; 36 ~WatchDog(); 37 38 /** 39 * Create a listening thread. Repeated calls do not take effect. 40 */ 41 void EnableWatchDog(); 42 43 /** 44 * End and destroy the listening thread. 45 */ 46 void DisableWatchDog(); 47 48 /** 49 * The listening thread enters the paused state (semaphore waiting). 50 */ 51 void PauseWatchDog(); 52 53 /** 54 * The listening thread resumes running and starts a new round of timeout waiting. 55 */ 56 void ResumeWatchDog(); 57 58 /** 59 * Watchdog feeding action. 60 * It needs to be called regularly within the timeoutMs_ time, otherwise Alarm() will be triggered. 61 * When the watchdog recovers, AlarmRecovery() will be triggered. 62 */ 63 void Notify(); 64 65 /** 66 * This event will be triggered when the watchdog times out. A timeout will only be triggered once. 67 * Please inherit and override the interface. 68 */ 69 virtual void Alarm(); 70 71 /** 72 * This event will be triggered when the watchdog is restored. 73 */ 74 virtual void AlarmRecovery(); 75 76 /** 77 * The thread used to monitor the watchdog. 78 * The watchdog timeout will trigger the Alarm() action and enter the pause state, 79 * until Notify() triggers the AlarmRecovery() again, and then continue to run. 80 */ 81 void WatchDogThread(); 82 83 void SetWatchDogTimeout(uint32_t timeoutMs); 84 85 private: 86 std::atomic<bool> disabling = false; 87 bool enable_ = false; 88 bool pause_ = false; 89 bool paused_ = false; 90 bool alarmed_ = false; 91 uint32_t timeoutMs_ = 1000; // Default 1000ms. 92 uint32_t count_ = 0; 93 std::condition_variable cond_; 94 std::mutex mutex_; 95 std::unique_ptr<std::thread> thread_; 96 }; 97 } // namespace Media 98 } // namespace OHOS 99 100 #endif 101