1 /* 2 * Copyright (c) 2021 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 HIDUMPER_UTILS_SP_SINGLETON_H 16 #define HIDUMPER_UTILS_SP_SINGLETON_H 17 #include <mutex> 18 #include <refbase.h> 19 #include "nocopyable.h" 20 namespace OHOS { 21 namespace HiviewDFX { 22 template<typename T> 23 class DelayedSpSingleton : public NoCopyable { 24 public: 25 static sptr<T> GetInstance(); 26 static void DestroyInstance(); 27 private: 28 static sptr<T> instance_; 29 static std::mutex mutex_; 30 }; 31 32 template<typename T> 33 sptr<T> DelayedSpSingleton<T>::instance_ = nullptr; 34 35 template<typename T> 36 std::mutex DelayedSpSingleton<T>::mutex_; 37 38 template<typename T> GetInstance()39sptr<T> DelayedSpSingleton<T>::GetInstance() 40 { 41 if (!instance_) { 42 std::lock_guard<std::mutex> lock(mutex_); 43 if (instance_ == nullptr) { 44 instance_ = new T(); 45 } 46 } 47 return instance_; 48 } 49 50 template<typename T> DestroyInstance()51void DelayedSpSingleton<T>::DestroyInstance() 52 { 53 std::lock_guard<std::mutex> lock(mutex_); 54 if (instance_) { 55 instance_.clear(); 56 instance_ = nullptr; 57 } 58 } 59 } // namespace HiviewDFX 60 } // namespace OHOS 61 #endif // HIDUMPER_UTILS_SP_SINGLETON_H 62