1 /* 2 * Copyright (C) 2024 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 #include "ctimer.h" 16 Start(unsigned int imsec,bool immediatelyRun)17void CTimer::Start(unsigned int imsec, bool immediatelyRun) 18 { 19 if (imsec == 0 || imsec == static_cast<unsigned int>(-1)) { 20 return; 21 } 22 exit.store(false); 23 msec = imsec; 24 this->immediatelyRun.store(immediatelyRun); 25 thread = std::thread([this]() { this->Run(); }); 26 } 27 Stop()28void CTimer::Stop() 29 { 30 exit.store(true); 31 cond.notify_all(); 32 if (thread.joinable()) { 33 thread.join(); 34 } 35 } 36 SetExit(bool exit)37void CTimer::SetExit(bool exit) 38 { 39 this->exit.store(exit); 40 } 41 Run()42void CTimer::Run() 43 { 44 if (immediatelyRun.load()) { 45 if (func) { 46 func(); 47 } 48 } 49 50 while (!exit.load()) { 51 { 52 std::unique_lock<std::mutex> locker(mutex); 53 cond.wait_for(locker, std::chrono::milliseconds(msec), [this]() { return exit.load(); }); 54 } 55 56 if (exit.load()) { 57 return; 58 } 59 60 if (func) { 61 func(); 62 } 63 } 64 }