1 /*
2 * Copyright (c) 2025-2025 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 #include "camera_simple_timer.h"
17
18 #include <chrono>
19
20 #include <thread>
21
22 namespace OHOS {
23 namespace CameraStandard {
24
SimpleTimer(std::function<void ()> fun)25 SimpleTimer::SimpleTimer(std::function<void()> fun) : innerFun_(fun) {
26 };
27
~SimpleTimer()28 SimpleTimer::~SimpleTimer()
29 {
30 std::unique_lock<std::mutex> lock(timerMtx_);
31 if (timerStatus_ == RUNNING) {
32 timerStatus_ = CANCEL;
33 timerCv_.notify_all();
34 timerCv_.wait(lock, [this]() { return timerStatus_ == DONE; });
35 } else if (timerStatus_ == CANCEL) {
36 timerCv_.wait(lock, [this]() { return timerStatus_ == DONE; });
37 }
38 }
39
InterruptableSleep(uint64_t timeoutMs)40 void SimpleTimer::InterruptableSleep(uint64_t timeoutMs)
41 {
42 std::unique_lock<std::mutex> lock(timerMtx_);
43 bool isWakeUp =
44 timerCv_.wait_for(lock, std::chrono::milliseconds(timeoutMs), [this] { return timerStatus_ != RUNNING; });
45 if (!isWakeUp && innerFun_ != nullptr) {
46 innerFun_();
47 }
48
49 timerStatus_ = DONE;
50 timerCv_.notify_all();
51 }
52
StartTask(uint64_t timeoutMs)53 bool SimpleTimer::StartTask(uint64_t timeoutMs)
54 {
55 std::unique_lock<std::mutex> lockStatus(timerMtx_);
56 if (timerStatus_ == RUNNING) {
57 return false;
58 }
59 timerStatus_ = RUNNING;
60 std::thread taskThread(&SimpleTimer::InterruptableSleep, this, timeoutMs);
61 taskThread.detach();
62 return true;
63 }
64
CancelTask()65 bool SimpleTimer::CancelTask()
66 {
67 std::unique_lock<std::mutex> lockStatus(timerMtx_);
68 if (timerStatus_ != RUNNING) {
69 return false;
70 }
71 timerStatus_ = CANCEL;
72 timerCv_.notify_all();
73 return true;
74 }
75 } // namespace CameraStandard
76 } // namespace OHOS