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 
16 #ifndef OHOS_MEDIA_DFX_WORKER_H
17 #define OHOS_MEDIA_DFX_WORKER_H
18 
19 #include <chrono>
20 #include <thread>
21 #include <queue>
22 #include <condition_variable>
23 
24 namespace OHOS {
25 namespace Media {
26 class DfxData {
27 public:
DfxData()28     DfxData() {};
~DfxData()29     virtual ~DfxData() {};
30 };
31 
32 using DfxExecute = void (*)(DfxData *data);
33 
34 class DfxTask {
35 public:
DfxTask(DfxExecute executor,DfxData * data)36     DfxTask(DfxExecute executor, DfxData *data) : executor_(executor), data_(data),
37         executeTime_{std::chrono::system_clock::now()}, isDelayTask_(false) {}
DfxTask()38     DfxTask() : DfxTask(nullptr, nullptr) {}
~DfxTask()39     virtual ~DfxTask()
40     {
41         delete data_;
42         data_ = nullptr;
43     }
44 
45     DfxExecute executor_;
46     DfxData *data_;
47     std::chrono::system_clock::time_point executeTime_;
48     bool isDelayTask_;
49 };
50 
51 class DfxWorker {
52 public:
53     DfxWorker();
54     ~DfxWorker();
55     static std::shared_ptr<DfxWorker> GetInstance();
56     void Init();
57     void End();
58     void AddTask(const std::shared_ptr<DfxTask> &task, int64_t delayTime = 0);
59     std::chrono::system_clock::time_point GetWaitTime();
60 
61 private:
62     void InitDelayThread();
63     void Prepare();
64     bool IsThumbnailUpdate();
65     bool IsDeleteStatisticUpdate();
66     void StartLoopTaskDelay();
67     bool IsTaskQueueEmpty();
68     void WaitForTask();
69     bool IsDelayTask();
70     std::shared_ptr<DfxTask> GetTask();
71 
72 private:
73     int32_t thumbnailVersion_ {0};
74     int32_t deleteStatisticVersion_ {0};
75     static std::shared_ptr<DfxWorker> dfxWorkerInstance_;
76     std::thread delayThread_;
77     bool isEnd_ = false;
78     std::mutex taskLock_;
79     std::mutex workLock_;
80     std::condition_variable workCv_;
81     std::vector<std::shared_ptr<DfxTask>> taskList_;
82     bool isThreadRunning_;
83 };
84 } // namespace Media
85 } // namespace OHOS
86 
87 #endif  // OHOS_MEDIA_DFX_WORKER_H