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_executor.h"
17
18 #include <thread>
19
20 #include "dh_context.h"
21 #include "distributed_hardware_log.h"
22 #include "event_bus.h"
23
24 namespace OHOS {
25 namespace DistributedHardware {
26 namespace {
27 const uint32_t MAX_TASK_QUEUE_LENGTH = 256;
28 }
29 IMPLEMENT_SINGLE_INSTANCE(TaskExecutor);
TaskExecutor()30 TaskExecutor::TaskExecutor() : taskThreadFlag_(true)
31 {
32 DHLOGI("Ctor TaskExecutor");
33 std::thread(&TaskExecutor::TriggerTask, this).detach();
34 }
35
~TaskExecutor()36 TaskExecutor::~TaskExecutor()
37 {
38 DHLOGI("Dtor TaskExecutor");
39 taskThreadFlag_ = false;
40 }
41
PushTask(const std::shared_ptr<Task> & task)42 void TaskExecutor::PushTask(const std::shared_ptr<Task>& task)
43 {
44 if (task == nullptr) {
45 DHLOGE("Task is null");
46 return;
47 }
48
49 {
50 DHLOGI("Push task: %s", task->GetId().c_str());
51 std::unique_lock<std::mutex> lock(taskQueueMtx_);
52 if (taskQueue_.size() > MAX_TASK_QUEUE_LENGTH) {
53 DHLOGE("Task queue is full");
54 return;
55 }
56 taskQueue_.push(task);
57 }
58
59 condVar_.notify_one();
60 }
61
PopTask()62 std::shared_ptr<Task> TaskExecutor::PopTask()
63 {
64 std::shared_ptr<Task> task = nullptr;
65
66 std::unique_lock<std::mutex> lock(taskQueueMtx_);
67 condVar_.wait(lock, [this] {
68 return !(this->taskQueue_.empty());
69 });
70
71 if (!taskQueue_.empty()) {
72 task = taskQueue_.front();
73 taskQueue_.pop();
74 DHLOGI("Pop task: %s", task->GetId().c_str());
75 }
76
77 return task;
78 }
79
TriggerTask()80 void TaskExecutor::TriggerTask()
81 {
82 while (taskThreadFlag_) {
83 std::shared_ptr<Task> task = PopTask();
84 if (task == nullptr) {
85 DHLOGE("Pop a null task, error");
86 continue;
87 }
88
89 auto taskFunc = [task]() {
90 task->DoTask();
91 };
92
93 DHLOGI("Post task to EventBus: %s", task->GetId().c_str());
94 DHContext::GetInstance().GetEventBus()->PostTask(taskFunc, task->GetId());
95 }
96 }
97 } // namespace DistributedHardware
98 } // namespace OHOS
99