1 /*
2  * Copyright (c) 2023-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 OHOS_DEFERRED_PROCESSING_SERVICE_TIMER_CORE_H
17 #define OHOS_DEFERRED_PROCESSING_SERVICE_TIMER_CORE_H
18 
19 #include <atomic>
20 #include <condition_variable>
21 #include <chrono>
22 #include <cstdint>
23 #include <map>
24 #include <memory>
25 #include <mutex>
26 #include <queue>
27 #include <thread>
28 #include <vector>
29 #include "timer.h"
30 
31 namespace OHOS {
32 namespace CameraStandard {
33 namespace DeferredProcessing {
34 class TimerCore {
35 public:
36     static TimerCore& GetInstance();
37     ~TimerCore();
38     bool Initialize();
39     bool RegisterTimer(uint64_t timestampMs, const std::shared_ptr<Timer>& timer);
40     bool DeregisterTimer(uint64_t timestampMs, const std::shared_ptr<Timer>& timer);
41 
42 private:
43     TimerCore();
44     void TimerLoop(const std::string& threadName);
45     std::chrono::milliseconds GetNextExpirationTimeUnlocked();
46     void DoTimeout();
47     bool IsSameOwner(const std::shared_ptr<Timer>& lhs, const std::weak_ptr<Timer>& rhs);
48 
49     std::mutex mutex_;
50     std::condition_variable cv_;
51     std::atomic<bool> active_{false};
52     std::atomic<bool> resetTimer_{false};
53     std::thread worker_{};
54     std::priority_queue<uint64_t, std::vector<uint64_t>, std::greater<uint64_t>> timeline_;
55     std::map<uint64_t, std::vector<std::weak_ptr<Timer>>> registeredTimers_{};
56 };
57 } //namespace DeferredProcessing
58 } // namespace CameraStandard
59 } // namespace OHOS
60 #endif // OHOS_DEFERRED_PROCESSING_SERVICE_TIMER_CORE_H
61