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 16 #ifndef JS_CONCURRENT_MODULE_TASKPOOL_TASK_MANAGER_H_ 17 #define JS_CONCURRENT_MODULE_TASKPOOL_TASK_MANAGER_H_ 18 19 #include <list> 20 #include <memory> 21 #include <set> 22 #include <shared_mutex> 23 #include <unordered_map> 24 25 #include "task_queue.h" 26 #include "napi/native_api.h" 27 28 namespace Commonlibrary::Concurrent::TaskPoolModule { 29 class Worker; 30 31 class TaskManager { 32 public: 33 TaskManager() = default; 34 ~TaskManager(); 35 36 static TaskManager &GetInstance(); 37 38 uint32_t GenerateTaskId(); 39 uint32_t GenerateExecuteId(); 40 TaskInfo* PopTaskInfo(uint32_t executeId); 41 void StoreTaskInfo(uint32_t executeId, TaskInfo* taskInfo); 42 void StoreStateInfo(uint32_t executeId, TaskState state); 43 void StoreRunningInfo(uint32_t taskId, uint32_t executeId); 44 bool UpdateState(uint32_t executeId, TaskState state); 45 void PopRunningInfo(uint32_t taskId, uint32_t executeId); 46 void EnqueueTask(std::unique_ptr<Task> task); 47 std::unique_ptr<Task> DequeueTask(); 48 void CancelTask(napi_env env, uint32_t taskId); 49 void NotifyWorkerIdle(Worker *worker); 50 void InitTaskRunner(napi_env env); 51 TaskInfo* GenerateTaskInfo(napi_env env, napi_value object, uint32_t taskId, uint32_t executeId); 52 void ReleaseTaskContent(TaskInfo* taskInfo); 53 54 private: 55 TaskManager(const TaskManager &) = delete; 56 TaskManager& operator=(const TaskManager &) = delete; 57 TaskManager(TaskManager &&) = delete; 58 TaskManager& operator=(TaskManager &&) = delete; 59 60 TaskState QueryState(uint32_t executeId); 61 62 bool NeedExpandWorker(); 63 64 void NotifyWorkerAdded(Worker *worker); 65 void NotifyExecuteTask(); 66 67 int32_t currentExecuteId_ = 0; 68 int32_t currentTaskId_ = 1; // 1: task will begin from 1, 0 for func 69 std::mutex idMutex_; 70 71 std::unordered_map<uint32_t, TaskInfo*> taskInfos_; 72 std::shared_mutex taskInfosMutex_; 73 74 std::unordered_map<uint32_t, TaskState> taskStates_; 75 std::shared_mutex taskStatesMutex_; 76 77 std::unordered_map<uint32_t, std::list<uint32_t>> runningInfos_; 78 std::shared_mutex runningInfosMutex_; 79 80 std::set<Worker*> workers_; 81 std::set<Worker*> idleWorkers_; 82 std::mutex workersMutex_; 83 84 TaskQueue taskQueue_; 85 }; 86 } // namespace Commonlibrary::Concurrent::TaskPoolModule 87 #endif // JS_CONCURRENT_MODULE_TASKPOOL_TASK_MANAGER_H_