1 /* 2 * Copyright (c) 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 DELEGATE_TASKS_H 16 #define DELEGATE_TASKS_H 17 #include <cinttypes> 18 #include <functional> 19 #include <future> 20 #include <memory> 21 #include <mutex> 22 #include <queue> 23 24 #include "id_factory.h" 25 #include "util.h" 26 27 namespace OHOS { 28 namespace MMI { 29 using DTaskCallback = std::function<int32_t()>; 30 class DelegateTasks : public IdFactory<int32_t> { 31 public: 32 struct TaskData { 33 uint64_t tid { 0 }; 34 int32_t taskId { 0 }; 35 }; 36 class Task : public std::enable_shared_from_this<Task> { 37 public: 38 using Promise = std::promise<int32_t>; 39 using Future = std::future<int32_t>; 40 using TaskPtr = std::shared_ptr<DelegateTasks::Task>; 41 Task(int32_t id, DTaskCallback fun, Promise *promise = nullptr) id_(id)42 : id_(id), fun_(fun), promise_(promise) {} 43 ~Task() = default; 44 void ProcessTask(); 45 GetId()46 int32_t GetId() const 47 { 48 return id_; 49 } GetSharedPtr()50 TaskPtr GetSharedPtr() 51 { 52 return shared_from_this(); 53 } SetWaited()54 void SetWaited() 55 { 56 hasWaited_ = true; 57 } 58 59 private: 60 std::atomic_bool hasWaited_ { false }; 61 int32_t id_ { 0 }; 62 DTaskCallback fun_; 63 Promise* promise_ { nullptr }; 64 }; 65 using TaskPtr = Task::TaskPtr; 66 using Promise = Task::Promise; 67 using Future = Task::Future; 68 69 public: 70 DelegateTasks() = default; 71 virtual ~DelegateTasks() = default; 72 73 bool Init(); 74 void ProcessTasks(); 75 int32_t PostSyncTask(DTaskCallback callback); 76 int32_t PostAsyncTask(DTaskCallback callback); 77 GetReadFd()78 int32_t GetReadFd() const 79 { 80 return fds_[0]; 81 } SetWorkerThreadId(uint64_t tid)82 void SetWorkerThreadId(uint64_t tid) 83 { 84 workerThreadId_ = tid; 85 } IsCallFromWorkerThread()86 bool IsCallFromWorkerThread() const 87 { 88 return (GetThisThreadId() == workerThreadId_); 89 } 90 91 private: 92 void PopPendingTaskList(std::vector<TaskPtr> &tasks); 93 TaskPtr PostTask(DTaskCallback callback, Promise *promise = nullptr); 94 95 private: 96 uint64_t workerThreadId_ { 0 }; 97 int32_t fds_[2] = {}; 98 std::mutex mux_; 99 std::queue<TaskPtr> tasks_; 100 }; 101 } // namespace MMI 102 } // namespace OHOS 103 #endif // DELEGATE_TASKS_H