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