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 CORE_THREADING_PARALLEL_QUEUE_H
17 #define CORE_THREADING_PARALLEL_QUEUE_H
18 
19 #include <base/containers/vector.h>
20 #include <core/namespace.h>
21 #include <core/threading/intf_thread_pool.h>
22 
23 #include "threading/task_queue.h"
24 
CORE_BEGIN_NAMESPACE()25 CORE_BEGIN_NAMESPACE()
26 // Non-thread safe parallel task queue, executes all tasks at once in parallel.
27 // This queue type is not thread safe and should be only used from one thread.
28 class ParallelTaskQueue final : public TaskQueue {
29 public:
30     /** Constructor for the parallel task queue.
31         @param threads Optional thread pool, if support for threading is desired.
32     */
33     explicit ParallelTaskQueue(const IThreadPool::Ptr& threadPool);
34     ParallelTaskQueue(const ParallelTaskQueue& other) = delete;
35     ~ParallelTaskQueue() override;
36 
37     /** Submit task to execution queue, to be run after another task.
38         @param afterIdentifier Identifier of the task that is run prior the submitted task.
39         @param taskIdentifier Identifier of the task, must be unique.
40         @param task Task to execute.
41     */
42     void SubmitAfter(uint64_t afterIdentifier, uint64_t taskIdentifier, IThreadPool::ITask::Ptr&& task);
43     void SubmitAfter(
44         BASE_NS::array_view<const uint64_t> afterIdentifiers, uint64_t taskIdentifier, IThreadPool::ITask::Ptr&& task);
45 
46     void Submit(uint64_t taskIdentifier, IThreadPool::ITask::Ptr&& task) override;
47     void Remove(uint64_t taskIdentifier) override;
48 
49     void Clear() override;
50 
51     void Execute() override;
52 
53 private:
54     struct TaskState;
55     class Task;
56 
57     void QueueTasks(BASE_NS::vector<size_t>& waiting, TaskState& taskState);
58 
59     BASE_NS::vector<TaskQueue::Entry> tasks_;
60 };
61 CORE_END_NAMESPACE()
62 
63 #endif // CORE_THREADING_TASK_QUEUE_H
64