1 /*
2 * Copyright (C) 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 #include "threading/sequential_task_queue.h"
17
18 #include <algorithm>
19
20 #include <core/log.h>
21 #include <core/namespace.h>
22
23 #include "os/platform.h"
24
CORE_BEGIN_NAMESPACE()25 CORE_BEGIN_NAMESPACE()
26 // -- Sequential task queue.
27 SequentialTaskQueue::SequentialTaskQueue(const IThreadPool::Ptr& threadPool) : TaskQueue(threadPool) {}
28
~SequentialTaskQueue()29 SequentialTaskQueue::~SequentialTaskQueue()
30 {
31 Wait();
32 }
33
Execute()34 void SequentialTaskQueue::Execute()
35 {
36 // A function that executes tasks one by one.
37 for (auto& entry : tasks_) {
38 (*entry.task)();
39 }
40 }
41
Submit(uint64_t taskIdentifier,IThreadPool::ITask::Ptr && task)42 void SequentialTaskQueue::Submit(uint64_t taskIdentifier, IThreadPool::ITask::Ptr&& task)
43 {
44 CORE_ASSERT(std::find(tasks_.begin(), tasks_.end(), taskIdentifier) == tasks_.end());
45
46 tasks_.emplace_back(taskIdentifier, std::move(task));
47 }
48
SubmitAfter(uint64_t afterIdentifier,uint64_t taskIdentifier,IThreadPool::ITask::Ptr && task)49 void SequentialTaskQueue::SubmitAfter(uint64_t afterIdentifier, uint64_t taskIdentifier, IThreadPool::ITask::Ptr&& task)
50 {
51 auto it = std::find(tasks_.begin(), tasks_.end(), afterIdentifier);
52 if (it != tasks_.end()) {
53 tasks_.emplace(++it, taskIdentifier, std::move(task));
54 } else {
55 tasks_.emplace_back(taskIdentifier, std::move(task));
56 }
57 }
58
SubmitBefore(uint64_t beforeIdentifier,uint64_t taskIdentifier,IThreadPool::ITask::Ptr && task)59 void SequentialTaskQueue::SubmitBefore(
60 uint64_t beforeIdentifier, uint64_t taskIdentifier, IThreadPool::ITask::Ptr&& task)
61 {
62 CORE_ASSERT(std::find(tasks_.begin(), tasks_.end(), taskIdentifier) == tasks_.end());
63
64 auto it = std::find(tasks_.begin(), tasks_.end(), beforeIdentifier);
65 if (it != tasks_.end()) {
66 tasks_.emplace(it, taskIdentifier, std::move(task));
67 }
68 }
69
Remove(uint64_t taskIdentifier)70 void SequentialTaskQueue::Remove(uint64_t taskIdentifier)
71 {
72 auto it = std::find(tasks_.begin(), tasks_.end(), taskIdentifier);
73 if (it != tasks_.end()) {
74 tasks_.erase(it);
75 }
76 }
77
Clear()78 void SequentialTaskQueue::Clear()
79 {
80 Wait();
81 tasks_.clear();
82 }
83 CORE_END_NAMESPACE()
84