1 /* 2 * Copyright (c) 2024 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_ASYNC_RUNNER_MANAGER_H 17 #define JS_CONCURRENT_MODULE_TASKPOOL_ASYNC_RUNNER_MANAGER_H 18 19 #include <mutex> 20 #include <unordered_map> 21 22 #include "async_runner.h" 23 #include "napi/native_api.h" 24 #include "task.h" 25 26 namespace Commonlibrary::Concurrent::TaskPoolModule { 27 using namespace Commonlibrary::Concurrent::Common::Helper; 28 29 class AsyncRunnerManager { 30 public: 31 static AsyncRunnerManager& GetInstance(); 32 AsyncRunner* CreateOrGetGlobalRunner(napi_env env, napi_value thisVar, const std::string& name, 33 uint32_t runningCapacity, uint32_t waitingCapacity); 34 bool TriggerAsyncRunner(napi_env env, Task* lastTask); 35 void StoreAsyncRunner(uint64_t asyncRunnerId, AsyncRunner* asyncRunner); 36 AsyncRunner* GetAsyncRunner(uint64_t asyncRunnerId); 37 void CancelAsyncRunnerTask(napi_env env, Task* task); 38 void RemoveWaitingTask(Task* task); 39 bool FindRunnerAndRef(uint64_t asyncRunnerId); 40 bool UnrefAndDestroyRunner(AsyncRunner* asyncRunner); 41 void DecreaseRunningCount(uint64_t asyncRunnerId); 42 43 private: 44 AsyncRunnerManager() = default; 45 ~AsyncRunnerManager() = default; 46 AsyncRunnerManager(const AsyncRunnerManager &) = delete; 47 AsyncRunnerManager& operator=(const AsyncRunnerManager &) = delete; 48 AsyncRunnerManager(AsyncRunnerManager &&) = delete; 49 AsyncRunnerManager& operator=(AsyncRunnerManager &&) = delete; 50 void RemoveAsyncRunner(uint64_t asyncRunnerId); 51 void RemoveGlobalAsyncRunner(const std::string& name); 52 53 // <asyncRunnerId, AsyncRunner> 54 std::unordered_map<uint64_t, AsyncRunner*> asyncRunners_ {}; 55 std::mutex asyncRunnersMutex_; 56 // <<name1, AsyncRunner>, <name2, AsyncRunner>, ...> 57 std::unordered_map<std::string, AsyncRunner*> globalAsyncRunner_ {}; 58 std::mutex globalAsyncRunnerMutex_; 59 }; 60 } // namespace Commonlibrary::Concurrent::TaskPoolModule 61 #endif // JS_CONCURRENT_MODULE_TASKPOOL_ASYNC_RUNNER_MANAGER_H