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 "ffrt_utils.h"
17
18 namespace OHOS {
19 namespace PowerMgr {
SubmitTask(const FFRTTask & task)20 void FFRTUtils::SubmitTask(const FFRTTask& task)
21 {
22 ffrt::submit(task);
23 }
24
SubmitTaskSync(const FFRTTask & task)25 void FFRTUtils::SubmitTaskSync(const FFRTTask& task)
26 {
27 ffrt::submit(task);
28 ffrt::wait();
29 }
30
SubmitQueueTasks(const std::vector<FFRTTask> & tasks,FFRTQueue & queue)31 void FFRTUtils::SubmitQueueTasks(const std::vector<FFRTTask>& tasks, FFRTQueue& queue)
32 {
33 if (tasks.empty()) {
34 return;
35 }
36 for (auto task : tasks) {
37 queue.submit(task);
38 }
39 }
40
SubmitDelayTask(FFRTTask & task,uint32_t delayMs,FFRTQueue & queue)41 FFRTHandle FFRTUtils::SubmitDelayTask(FFRTTask& task, uint32_t delayMs, FFRTQueue& queue)
42 {
43 using namespace std::chrono;
44 milliseconds ms(delayMs);
45 microseconds us = duration_cast<microseconds>(ms);
46 return queue.submit_h(task, ffrt::task_attr().delay(us.count()));
47 }
48
SubmitTimeoutTask(const FFRTTask & task,uint32_t timeoutMs)49 bool FFRTUtils::SubmitTimeoutTask(const FFRTTask& task, uint32_t timeoutMs)
50 {
51 ffrt::future<void> future = ffrt::async(task);
52 auto status = future.wait_for(std::chrono::milliseconds(timeoutMs));
53 return status == ffrt::future_status::ready;
54 }
55
CancelTask(FFRTHandle & handle,FFRTQueue & queue)56 void FFRTUtils::CancelTask(FFRTHandle& handle, FFRTQueue& queue)
57 {
58 queue.cancel(handle);
59 }
60
Mutex()61 FFRTUtils::Mutex::Mutex()
62 {
63 mutex_ = new ffrt::mutex();
64 }
65
~Mutex()66 FFRTUtils::Mutex::~Mutex()
67 {
68 if (!mutex_) {
69 return;
70 }
71 mutex_ = nullptr;
72 delete mutex_;
73 }
74
Lock()75 void FFRTUtils::Mutex::Lock()
76 {
77 if (!mutex_) {
78 return;
79 }
80 mutex_->lock();
81 }
82
TryLock()83 bool FFRTUtils::Mutex::TryLock()
84 {
85 if (!mutex_) {
86 return false;
87 }
88 return mutex_->try_lock();
89 }
90
Unlock()91 void FFRTUtils::Mutex::Unlock()
92 {
93 if (!mutex_) {
94 return;
95 }
96 mutex_->unlock();
97 }
98 } // namespace PowerMgr
99 } // namespace OHOS