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