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 #include "util/task/task_manager.h"
17 #include <atomic>
18 #include "ffrt.h"
19
20 namespace OHOS {
21 namespace Media {
TaskManager(std::string name,TaskManagerTimeOpt opt)22 TaskManager::TaskManager(std::string name, TaskManagerTimeOpt opt) : taskName_(std::move(name)), m_timeOpt(opt)
23 {
24 Init();
25 }
26
~TaskManager()27 TaskManager::~TaskManager()
28 {
29 Wait();
30 }
31
Init()32 void TaskManager::Init()
33 {
34 if (m_timeOpt == TaskManagerTimeOpt::SEQUENTIAL) {
35 m_taskQueue = std::make_shared<ffrt::queue>(taskName_.c_str(), ffrt::queue_attr().qos(ffrt_qos_utility));
36 }
37 }
38
Submit(const std::function<void ()> & func,std::string funcName)39 void TaskManager::Submit(const std::function<void()>& func, std::string funcName)
40 {
41 m_taskCnt++;
42 if (m_timeOpt == TaskManagerTimeOpt::SEQUENTIAL && m_taskQueue) {
43 m_taskQueue->submit([this, func, funcName]() { this->RunTask(func, funcName); });
44 } else {
45 ffrt::submit([this, func, funcName]() { this->RunTask(func, funcName); });
46 }
47 }
48
GetTaskCount() const49 uint32_t TaskManager::GetTaskCount() const
50 {
51 return m_taskCnt;
52 }
53
Wait(std::vector<TaskHandle> & taskHandles)54 void TaskManager::Wait(std::vector<TaskHandle>& taskHandles)
55 {
56 if (m_timeOpt == TaskManagerTimeOpt::SEQUENTIAL && m_taskQueue) {
57 for (TaskHandle& taskHandle : taskHandles) {
58 m_taskQueue->wait(taskHandle);
59 }
60 } else {
61 std::vector<ffrt::dependence> deps;
62 deps.insert(deps.end(), taskHandles.begin(), taskHandles.end());
63 ffrt::wait(deps);
64 }
65 }
66
RunTask(const std::function<void ()> & func,const std::string &)67 void TaskManager::RunTask(const std::function<void()>& func, const std::string&)
68 {
69 func();
70 {
71 std::unique_lock lk(m_taskCntLock);
72 m_taskCnt--;
73 }
74
75 m_taskCv.notify_all();
76 }
77
Wait()78 void TaskManager::Wait()
79 {
80 if (m_timeOpt == TaskManagerTimeOpt::SEQUENTIAL && m_taskQueue) {
81 auto handle = m_taskQueue->submit_h([&] { });
82 m_taskQueue->wait(handle);
83 } else {
84 std::unique_lock lk(m_taskCntLock);
85 if (m_taskCnt > 0) {
86 m_taskCv.wait(lk, [&] { return m_taskCnt == 0; });
87 }
88 }
89 }
90 } // namespace Media
91 } // namespace OHOS