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