• 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_board.h"
17 
18 #include "dh_context.h"
19 #include "dh_utils_tool.h"
20 #include "distributed_hardware_errno.h"
21 #include "distributed_hardware_log.h"
22 
23 namespace OHOS {
24 namespace DistributedHardware {
25 #undef DH_LOG_TAG
26 #define DH_LOG_TAG "TaskBoard"
27 
28 constexpr int32_t TASK_TIMEOUT_MS = 5000;
29 
30 IMPLEMENT_SINGLE_INSTANCE(TaskBoard);
31 
WaitForALLTaskFinish()32 int32_t TaskBoard::WaitForALLTaskFinish()
33 {
34     // wait for all task finish until timeout
35     std::unique_lock<std::mutex> lock(tasksMtx_);
36     auto status = conVar_.wait_for(lock, std::chrono::milliseconds(TASK_TIMEOUT_MS),
37         [this]() { return tasks_.empty(); });
38     if (!status) {
39         DHLOGE("wait for all task finish timeout");
40         return ERR_DH_FWK_TASK_TIMEOUT;
41     }
42     DHLOGI("all task finished");
43 
44     return DH_FWK_SUCCESS;
45 }
46 
IsAllTaskFinish()47 bool TaskBoard::IsAllTaskFinish()
48 {
49     std::lock_guard<std::mutex> lock(tasksMtx_);
50     return this->tasks_.empty();
51 }
52 
AddTask(std::shared_ptr<Task> task)53 void TaskBoard::AddTask(std::shared_ptr<Task> task)
54 {
55     if (task == nullptr) {
56         DHLOGE("task is null, error");
57         return;
58     }
59 
60     std::lock_guard<std::mutex> lock(tasksMtx_);
61     DHLOGI("Add task, id: %s", task->GetId().c_str());
62     if (this->tasks_.find(task->GetId()) != this->tasks_.end()) {
63         DHLOGE("Task id duplicate, id: %d", task->GetId().c_str());
64         return;
65     }
66     this->tasks_.emplace(task->GetId(), task);
67 }
68 
RemoveTask(std::string taskId)69 void TaskBoard::RemoveTask(std::string taskId)
70 {
71     std::lock_guard<std::mutex> lock(tasksMtx_);
72     DHLOGI("Remove task, id: %s", taskId.c_str());
73     RemoveTaskInner(taskId);
74     if (tasks_.empty()) {
75         conVar_.notify_one();
76     }
77 }
78 
RemoveTaskInner(std::string taskId)79 void TaskBoard::RemoveTaskInner(std::string taskId)
80 {
81     if (tasks_.find(taskId) == tasks_.end()) {
82         DHLOGE("Can not find removed task");
83         return;
84     }
85 
86     tasks_.erase(taskId);
87 }
88 }
89 }
90