1cc290419Sopenharmony_ci/* 2cc290419Sopenharmony_ci * Copyright (C) 2024 Huawei Device Co., Ltd. 3cc290419Sopenharmony_ci * Licensed under the Apache License, Version 2.0 (the "License"); 4cc290419Sopenharmony_ci * you may not use this file except in compliance with the License. 5cc290419Sopenharmony_ci * You may obtain a copy of the License at 6cc290419Sopenharmony_ci * 7cc290419Sopenharmony_ci * http://www.apache.org/licenses/LICENSE-2.0 8cc290419Sopenharmony_ci * 9cc290419Sopenharmony_ci * Unless required by applicable law or agreed to in writing, software 10cc290419Sopenharmony_ci * distributed under the License is distributed on an "AS IS" BASIS, 11cc290419Sopenharmony_ci * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12cc290419Sopenharmony_ci * See the License for the specific language governing permissions and 13cc290419Sopenharmony_ci * limitations under the License. 14cc290419Sopenharmony_ci */ 15cc290419Sopenharmony_ci#include "ctimer.h" 16cc290419Sopenharmony_ci 17cc290419Sopenharmony_civoid CTimer::Start(unsigned int imsec, bool immediatelyRun) 18cc290419Sopenharmony_ci{ 19cc290419Sopenharmony_ci if (imsec == 0 || imsec == static_cast<unsigned int>(-1)) { 20cc290419Sopenharmony_ci return; 21cc290419Sopenharmony_ci } 22cc290419Sopenharmony_ci exit.store(false); 23cc290419Sopenharmony_ci msec = imsec; 24cc290419Sopenharmony_ci this->immediatelyRun.store(immediatelyRun); 25cc290419Sopenharmony_ci thread = std::thread([this]() { this->Run(); }); 26cc290419Sopenharmony_ci} 27cc290419Sopenharmony_ci 28cc290419Sopenharmony_civoid CTimer::Stop() 29cc290419Sopenharmony_ci{ 30cc290419Sopenharmony_ci exit.store(true); 31cc290419Sopenharmony_ci cond.notify_all(); 32cc290419Sopenharmony_ci if (thread.joinable()) { 33cc290419Sopenharmony_ci thread.join(); 34cc290419Sopenharmony_ci } 35cc290419Sopenharmony_ci} 36cc290419Sopenharmony_ci 37cc290419Sopenharmony_civoid CTimer::SetExit(bool exit) 38cc290419Sopenharmony_ci{ 39cc290419Sopenharmony_ci this->exit.store(exit); 40cc290419Sopenharmony_ci} 41cc290419Sopenharmony_ci 42cc290419Sopenharmony_civoid CTimer::Run() 43cc290419Sopenharmony_ci{ 44cc290419Sopenharmony_ci if (immediatelyRun.load()) { 45cc290419Sopenharmony_ci if (func) { 46cc290419Sopenharmony_ci func(); 47cc290419Sopenharmony_ci } 48cc290419Sopenharmony_ci } 49cc290419Sopenharmony_ci 50cc290419Sopenharmony_ci while (!exit.load()) { 51cc290419Sopenharmony_ci { 52cc290419Sopenharmony_ci std::unique_lock<std::mutex> locker(mutex); 53cc290419Sopenharmony_ci cond.wait_for(locker, std::chrono::milliseconds(msec), [this]() { return exit.load(); }); 54cc290419Sopenharmony_ci } 55cc290419Sopenharmony_ci 56cc290419Sopenharmony_ci if (exit.load()) { 57cc290419Sopenharmony_ci return; 58cc290419Sopenharmony_ci } 59cc290419Sopenharmony_ci 60cc290419Sopenharmony_ci if (func) { 61cc290419Sopenharmony_ci func(); 62cc290419Sopenharmony_ci } 63cc290419Sopenharmony_ci } 64cc290419Sopenharmony_ci}