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 AUDIO_TIMER_H 17 #define AUDIO_TIMER_H 18 19 #include <atomic> 20 #include <condition_variable> 21 #include <mutex> 22 #include <thread> 23 24 namespace OHOS { 25 namespace AudioStandard { 26 const int WAIT_TIMEOUT_IN_SECS = 5; 27 28 class AudioTimer { 29 public: AudioTimer()30 AudioTimer() 31 { 32 timeoutDuration = WAIT_TIMEOUT_IN_SECS; 33 isTimerStarted = false; 34 isTimedOut = false; 35 exitLoop = false; 36 timerLoop = std::thread(&AudioTimer::TimerLoopFunc, this); 37 pthread_setname_np(timerLoop.native_handle(), "AudioTimer"); 38 } 39 ~AudioTimer()40 ~AudioTimer() 41 { 42 { 43 std::unique_lock<std::mutex> lck(timerMutex); 44 exitLoop = true; 45 isTimerStarted = !isTimerStarted; 46 timerCtrl.notify_one(); 47 } 48 timerLoop.join(); 49 } 50 StartTimer(uint32_t duration)51 void StartTimer(uint32_t duration) 52 { 53 std::unique_lock<std::mutex> lck(timerMutex); 54 timeoutDuration = duration; 55 isTimerStarted = true; 56 timerCtrl.notify_one(); 57 } 58 StopTimer()59 void StopTimer() 60 { 61 std::unique_lock<std::mutex> lck(timerMutex); 62 isTimerStarted = false; 63 if (!isTimedOut) { 64 timerCtrl.notify_one(); 65 } 66 } 67 IsTimeOut()68 bool IsTimeOut() 69 { 70 return isTimedOut; 71 } 72 73 virtual void OnTimeOut() = 0; 74 75 volatile std::atomic<bool> isTimedOut; 76 77 private: 78 std::thread timerLoop; 79 std::condition_variable timerCtrl; 80 volatile std::atomic<bool> isTimerStarted; 81 std::mutex timerMutex; 82 volatile bool exitLoop; 83 uint32_t timeoutDuration; 84 TimerLoopFunc()85 void TimerLoopFunc() 86 { 87 while (true) { 88 std::unique_lock<std::mutex> lck(timerMutex); 89 if (exitLoop) { 90 break; 91 } 92 if (isTimerStarted) { 93 if (!timerCtrl.wait_for(lck, std::chrono::seconds(timeoutDuration), 94 [this] { return CheckTimerStopped(); })) { 95 isTimedOut = true; 96 isTimerStarted = false; 97 OnTimeOut(); 98 } 99 } else { 100 timerCtrl.wait(lck, [this] { return CheckTimerStarted(); }); 101 isTimedOut = false; 102 } 103 } 104 } 105 CheckTimerStarted()106 bool CheckTimerStarted() 107 { 108 return this->isTimerStarted; 109 } 110 CheckTimerStopped()111 bool CheckTimerStopped() 112 { 113 return !this->isTimerStarted; 114 } 115 }; 116 } // namespace AudioStandard 117 } // namespace OHOS 118 #endif // AUDIO_TIMER_H 119