1 /* 2 * Copyright (c) 2023 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 #ifndef HGM_TASK_HANDLE_THREAD_H 17 #define HGM_TASK_HANDLE_THREAD_H 18 19 #include <future> 20 #include <thread> 21 #include <unordered_map> 22 #include <unordered_set> 23 #include "event_handler.h" 24 #include "refbase.h" 25 26 namespace OHOS::Rosen { 27 namespace HgmDetail { 28 template<typename Task> 29 class ScheduledTask : public RefBase { 30 public: Create(Task && task)31 static auto Create(Task&& task) 32 { 33 sptr<ScheduledTask<Task>> t(new ScheduledTask(std::forward<Task&&>(task))); 34 return std::make_pair(t, t->task_.get_future()); 35 } 36 Run()37 void Run() 38 { 39 task_(); 40 } 41 42 private: ScheduledTask(Task && task)43 explicit ScheduledTask(Task&& task) : task_(std::move(task)) {} 44 ~ScheduledTask() override = default; 45 46 using Return = std::invoke_result_t<Task>; 47 std::packaged_task<Return()> task_; 48 }; 49 } // namespace HgmDetail 50 51 class HgmTaskHandleThread { 52 public: 53 static HgmTaskHandleThread& Instance(); GetRunner()54 const std::shared_ptr<AppExecFwk::EventRunner>& GetRunner() const { return runner_; } 55 std::shared_ptr<AppExecFwk::EventHandler> CreateHandler(); 56 void PostTask(const std::function<void()>& task, int64_t delayTime = 0); 57 bool PostSyncTask(const std::function<void()>& task); 58 void PostEvent(std::string eventId, const std::function<void()>& task, int64_t delayTime = 0); 59 void DetectMultiThreadingCalls(); 60 void RemoveEvent(std::string eventId); 61 template<typename Task, typename Return = std::invoke_result_t<Task>> ScheduleTask(Task && task)62 std::future<Return> ScheduleTask(Task&& task) 63 { 64 auto [scheduledTask, taskFuture] = HgmDetail::ScheduledTask<Task>::Create(std::forward<Task&&>(task)); 65 PostTask([t(std::move(scheduledTask))]() { t->Run(); }); 66 return std::move(taskFuture); 67 } 68 69 private: 70 HgmTaskHandleThread(); 71 ~HgmTaskHandleThread() = default; 72 HgmTaskHandleThread(const HgmTaskHandleThread&); 73 HgmTaskHandleThread(const HgmTaskHandleThread&&); 74 HgmTaskHandleThread& operator=(const HgmTaskHandleThread&); 75 HgmTaskHandleThread& operator=(const HgmTaskHandleThread&&); 76 77 std::shared_ptr<AppExecFwk::EventRunner> runner_ = nullptr; 78 std::shared_ptr<AppExecFwk::EventHandler> handler_ = nullptr; 79 int32_t curThreadId_ = -1; 80 }; 81 } 82 #endif // HGM_TASK_HANDLE_THREAD_H 83