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 #ifndef OHOS_APP_DISPATCHER_BARRIER_HANDLER_H 16 #define OHOS_APP_DISPATCHER_BARRIER_HANDLER_H 17 18 #include <set> 19 #include "appexecfwk_errors.h" 20 #include "task.h" 21 #include "task_listener.h" 22 #include "task_executor.h" 23 #include "task_execute_interceptor.h" 24 #include "task_stage.h" 25 26 namespace OHOS { 27 namespace AppExecFwk { 28 29 class BarrierHandler : public TaskExecuteInterceptor { 30 public: 31 BarrierHandler(const std::shared_ptr<TaskExecutor> &executor); 32 ~BarrierHandler() = default; 33 /** 34 * Intercept executing a task. 35 */ 36 ErrCode Intercept(std::shared_ptr<Task> &task) override; 37 38 /** 39 * Adds a task with barrier semantics. 40 */ 41 ErrCode AddBarrier(std::shared_ptr<Task> &barrierTask); 42 43 private: 44 ErrCode ListenToTask(std::shared_ptr<Task> &task); 45 void OnTaskDone(std::shared_ptr<Task> &task); 46 bool AddTaskAfterBarrier(std::shared_ptr<Task> &task); 47 bool HasTask(const std::set<std::shared_ptr<Task>> &tasks); 48 std::set<std::shared_ptr<Task>> CreateTaskSet(std::shared_ptr<Task> &firstTask); 49 50 private: 51 class BarrierPair { 52 public: 53 std::set<std::shared_ptr<Task>> tasks_; 54 std::shared_ptr<Task> barrier_; 55 BarrierPair(const std::set<std::shared_ptr<Task>> & tasks,const std::shared_ptr<Task> & barrier)56 BarrierPair(const std::set<std::shared_ptr<Task>> &tasks, const std::shared_ptr<Task> &barrier) 57 { 58 tasks_ = tasks; 59 barrier_ = barrier; 60 }; 61 ~BarrierPair() = default; 62 }; 63 64 class MyTaskListener : public TaskListener { 65 private: 66 std::function<void()> callback_; 67 68 public: OnChanged(const TaskStage & stage)69 void OnChanged(const TaskStage &stage) 70 { 71 if (stage.IsDone()) { 72 APP_LOGI("BarrierHandler task done."); 73 callback_(); 74 } 75 }; 76 // set callback function Callback(const std::function<void ()> & callbackFunction)77 void Callback(const std::function<void()> &callbackFunction) 78 { 79 callback_ = std::move(callbackFunction); 80 }; 81 }; 82 83 std::mutex barrierLock_; 84 std::shared_ptr<TaskExecutor> executor_; 85 std::deque<std::shared_ptr<BarrierPair>> barrierQueue_; 86 }; 87 88 } // namespace AppExecFwk 89 } // namespace OHOS 90 91 #endif