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_DISPATHCER_TASK_QUEUE_H
17 #define CORE_THREADING_DISPATHCER_TASK_QUEUE_H
18 
19 #include <deque>
20 #include <mutex>
21 
22 #include <base/containers/string_view.h>
23 #include <base/containers/vector.h>
24 #include <core/namespace.h>
25 #include <core/threading/intf_thread_pool.h>
26 
27 #include "threading/task_queue.h"
28 
CORE_BEGIN_NAMESPACE()29 CORE_BEGIN_NAMESPACE()
30 // Thread safe task dispatcher, executes one task per execute call and removes it once it is finished.
31 class DispatcherTaskQueue final : public TaskQueue {
32 public:
33     /** Constructor for the dispatcher task queue.
34         @param threads Optional thread pool, if support for threading is desired.
35     */
36     explicit DispatcherTaskQueue(const IThreadPool::Ptr& threadPool);
37     DispatcherTaskQueue(const DispatcherTaskQueue& other) = delete;
38     ~DispatcherTaskQueue() override;
39 
40     /** Reports finished tasks, allows to check which tasks have been completed.
41         @return Task ids of tasks that have finished.
42     */
43     BASE_NS::vector<uint64_t> CollectFinishedTasks();
44 
45     void Submit(uint64_t taskIdentifier, IThreadPool::ITask::Ptr&& task) override;
46     void SubmitAfter(uint64_t afterIdentifier, uint64_t taskIdentifier, IThreadPool::ITask::Ptr&& task);
47     void SubmitAfter(
48         BASE_NS::array_view<const uint64_t> afterIdentifiers, uint64_t taskIdentifier, IThreadPool::ITask::Ptr&& task);
49     void Remove(uint64_t taskIdentifier) override;
50 
51     void Clear() override;
52 
53     void Execute() override;
54 
55 private:
56     std::deque<Entry> tasks_;
57     BASE_NS::vector<Entry> finishedTasks_;
58     std::mutex queueLock_;
59 };
60 CORE_END_NAMESPACE()
61 
62 #endif // CORE_THREADING_DISPATHCER_TASK_QUEUE_H
63