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