• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 #ifndef COMMON_COMPONENTS_TASKPOOL_TASK_QUEUE_H
17 #define COMMON_COMPONENTS_TASKPOOL_TASK_QUEUE_H
18 
19 #include <algorithm>
20 #include <atomic>
21 #include <chrono>
22 #include <deque>
23 #include <functional>
24 #include <map>
25 #include <memory>
26 #include <mutex>
27 #include <condition_variable>
28 
29 #include "common_components/taskpool/task.h"
30 #include "common_interfaces/base/common.h"
31 
32 namespace common {
33 using SteadyTimePoint = std::chrono::steady_clock::time_point;
34 class TaskQueue {
35 public:
36     TaskQueue() = default;
37     ~TaskQueue() = default;
38 
39     NO_COPY_SEMANTIC_CC(TaskQueue);
40     NO_MOVE_SEMANTIC_CC(TaskQueue);
41 
42     void PostTask(std::unique_ptr<Task> task);
43     void PostDelayedTask(std::unique_ptr<Task> task, uint64_t delayMilliseconds);
44     std::unique_ptr<Task> PopTask();
45 
46     void Terminate();
47     void TerminateTask(int32_t id, TaskType type);
48     void ForEachTask(const std::function<void(Task*)> &f);
49 
50 private:
51     void MoveExpiredTask(std::unique_lock<std::mutex> &lock);
52     void WaitForTask(std::unique_lock<std::mutex> &lock);
53 
54     std::deque<std::unique_ptr<Task>> tasks_;
55 
56     struct DelayedTaskCompare {
operatorDelayedTaskCompare57         bool operator()(const SteadyTimePoint& left, const SteadyTimePoint& right) const
58         {
59             return (std::chrono::duration_cast<std::chrono::duration<double>>(right - left)).count() > 0;
60         }
61     };
62 
63     std::multimap<SteadyTimePoint, std::unique_ptr<Task>, DelayedTaskCompare> delayedTasks_;
64 
65     std::atomic_bool terminate_ = false;
66     std::mutex mtx_;
67     std::condition_variable cv_;
68 };
69 }  // namespace common
70 #endif  // COMMON_COMPONENTS_TASKPOOL_TASK_QUEUE_H
71