• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 "task_queue.h"
17 #include "media_log.h"
18 #include "media_errors.h"
19 
20 namespace {
21     constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN, "TaskQueue"};
22 }
23 
24 namespace OHOS {
25 namespace Media {
~TaskQueue()26 TaskQueue::~TaskQueue()
27 {
28     (void)Stop();
29 }
30 
Start()31 int32_t TaskQueue::Start()
32 {
33     std::unique_lock<std::mutex> lock(mutex_);
34     if (thread_ != nullptr) {
35         MEDIA_LOGW("Started already, ignore ! [%{public}s]", name_.c_str());
36         return MSERR_OK;
37     }
38     isExit_ = false;
39     thread_ = std::make_unique<std::thread>(&TaskQueue::TaskProcessor, this);
40 
41     return MSERR_OK;
42 }
43 
Stop()44 int32_t TaskQueue::Stop() noexcept
45 {
46     std::unique_lock<std::mutex> lock(mutex_);
47     if (isExit_) {
48         MEDIA_LOGI("Stopped already, ignore ! [%{public}s]", name_.c_str());
49         return MSERR_OK;
50     }
51 
52     if (std::this_thread::get_id() == thread_->get_id()) {
53         MEDIA_LOGI("Stop at the task thread, reject");
54         return MSERR_INVALID_OPERATION;
55     }
56 
57     std::unique_ptr<std::thread> t;
58     isExit_ = true;
59     cond_.notify_all();
60     std::swap(thread_, t);
61     lock.unlock();
62 
63     if (t != nullptr && t->joinable()) {
64         t->join();
65     }
66 
67     lock.lock();
68     CancelNotExecutedTaskLocked();
69     return MSERR_OK;
70 }
71 
72 // cancelNotExecuted = false, delayUs = 0ULL.
EnqueueTask(const std::shared_ptr<ITaskHandler> & task,bool cancelNotExecuted,uint64_t delayUs)73 int32_t TaskQueue::EnqueueTask(const std::shared_ptr<ITaskHandler> &task, bool cancelNotExecuted, uint64_t delayUs)
74 {
75     constexpr uint64_t MAX_DELAY_US = 10000000ULL; // max delay.
76 
77     CHECK_AND_RETURN_RET_LOG(task != nullptr, MSERR_INVALID_VAL,
78         "Enqueue task when taskqueue task is nullptr.[%{public}s]", name_.c_str());
79 
80     task->Clear();
81 
82     CHECK_AND_RETURN_RET_LOG(delayUs < MAX_DELAY_US, MSERR_INVALID_VAL,
83         "Enqueue task when taskqueue delayUs[%{public}" PRIu64 "] is >= max delayUs[ %{public}" PRIu64
84         "], invalid! [%{public}s]",
85         delayUs, MAX_DELAY_US, name_.c_str());
86 
87     std::unique_lock<std::mutex> lock(mutex_);
88     CHECK_AND_RETURN_RET_LOG(!isExit_, MSERR_INVALID_OPERATION,
89         "Enqueue task when taskqueue is stopped, failed ! [%{public}s]", name_.c_str());
90 
91     if (cancelNotExecuted) {
92         CancelNotExecutedTaskLocked();
93     }
94 
95     // 1000 is ns to us.
96     constexpr uint32_t US_TO_NS = 1000;
97     uint64_t curTimeNs = static_cast<uint64_t>(std::chrono::steady_clock::now().time_since_epoch().count());
98     CHECK_AND_RETURN_RET_LOG(curTimeNs < UINT64_MAX - delayUs * US_TO_NS, MSERR_INVALID_OPERATION,
99         "Enqueue task but timestamp is overflow, why? [%{public}s]", name_.c_str());
100 
101     uint64_t executeTimeNs = delayUs * US_TO_NS + curTimeNs;
102     auto iter = std::find_if(taskList_.begin(), taskList_.end(), [executeTimeNs](const TaskHandlerItem &item) {
103         return (item.executeTimeNs_ > executeTimeNs);
104     });
105     (void)taskList_.insert(iter, {task, executeTimeNs});
106     cond_.notify_all();
107 
108     return 0;
109 }
110 
CancelNotExecutedTaskLocked()111 void TaskQueue::CancelNotExecutedTaskLocked()
112 {
113     MEDIA_LOGI("All task not executed are being cancelled..........[%{public}s]", name_.c_str());
114     while (!taskList_.empty()) {
115         std::shared_ptr<ITaskHandler> task = taskList_.front().task_;
116         taskList_.pop_front();
117         if (task != nullptr) {
118             task->Cancel();
119         }
120     }
121 }
122 
TaskProcessor()123 void TaskQueue::TaskProcessor()
124 {
125     MEDIA_LOGI("Enter TaskProcessor [%{public}s]", name_.c_str());
126     while (true) {
127         std::unique_lock<std::mutex> lock(mutex_);
128         cond_.wait(lock, [this] { return isExit_ || !taskList_.empty(); });
129         if (isExit_) {
130             MEDIA_LOGI("Exit TaskProcessor [%{public}s]", name_.c_str());
131             return;
132         }
133         TaskHandlerItem item = taskList_.front();
134         uint64_t curTimeNs = static_cast<uint64_t>(std::chrono::steady_clock::now().time_since_epoch().count());
135         if (curTimeNs >= item.executeTimeNs_) {
136             taskList_.pop_front();
137         } else {
138             uint64_t diff =  item.executeTimeNs_ - curTimeNs;
139             (void)cond_.wait_for(lock, std::chrono::nanoseconds(diff));
140             continue;
141         }
142         lock.unlock();
143 
144         if (item.task_ == nullptr || item.task_->IsCanceled()) {
145             MEDIA_LOGD("task is nullptr or task canceled. [%{public}s]", name_.c_str());
146             continue;
147         }
148 
149         item.task_->Execute();
150         if (item.task_->GetAttribute().periodicTimeUs_ == UINT64_MAX) {
151             continue;
152         }
153         int32_t res = EnqueueTask(item.task_, false, item.task_->GetAttribute().periodicTimeUs_);
154         if (res != MSERR_OK) {
155             MEDIA_LOGW("enqueue periodic task failed:%d, why? [%{public}s]", res, name_.c_str());
156         }
157     }
158     MEDIA_LOGI("Leave TaskProcessor [%{public}s]", name_.c_str());
159 }
160 } // namespace Media
161 } // namespace OHOS
162