1 /* 2 * Copyright (c) 2025 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_UTILS_CONDITION_VARIABLE_H 17 #define JS_CONCURRENT_MODULE_UTILS_CONDITION_VARIABLE_H 18 19 #include <cstdint> 20 #include <deque> 21 #include <mutex> 22 #include <string> 23 #include <unordered_map> 24 #include "condition_task.h" 25 26 namespace Commonlibrary::Concurrent::Condition { 27 28 class ConditionVariable { 29 public: 30 ConditionVariable(); 31 explicit ConditionVariable(const std::string &name); 32 33 static ConditionVariable *FindOrCreateCondition(const std::string &name); 34 void TryRemoveCondition(); 35 36 void AddTask(napi_env env, napi_deferred deferred, uint64_t timeout = -1); 37 void FinishTask(bool finishAll = false); 38 void FindAndFinishTask(ConditionTask *task, ConditionTaskFinishReason reason); 39 40 private: 41 static std::unordered_map<std::string, ConditionVariable *> condMap_; 42 static std::mutex mapMtx_; 43 44 uint32_t GetRefCount(); 45 void IncreaseRefCount(); 46 void DecreaseRefCount(); 47 48 std::string name_ {}; 49 std::deque<ConditionTask *> tasks_; 50 uint32_t refCount_ {0}; 51 std::mutex mtx_; 52 }; 53 54 } // namespace Commonlibrary::Concurrent::Condition 55 56 #endif 57