• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 WORKSCHED_SP_SINGLETON_H
17 #define WORKSCHED_SP_SINGLETON_H
18 
19 #include <mutex>
20 #include <memory>
21 #include <refbase.h>
22 #include "nocopyable.h"
23 
24 namespace OHOS {
25 namespace WorkScheduler {
26 #define DECLARE_DELAYED_SP_SINGLETON(MyClass) \
27 public:                                       \
28     ~MyClass();                               \
29 private:                                      \
30     friend DelayedSpSingleton<MyClass>;       \
31     MyClass();
32 
33 template<typename T>
34 class DelayedSpSingleton : public NoCopyable {
35 public:
36     static sptr<T> GetInstance();
37     static void DestroyInstance();
38 private:
39     static sptr<T> instance_;
40     static std::mutex mutex_;
41 };
42 
43 template<typename T>
44 sptr<T> DelayedSpSingleton<T>::instance_ = nullptr;
45 
46 template<typename T>
47 std::mutex DelayedSpSingleton<T>::mutex_;
48 
49 template<typename T>
GetInstance()50 sptr<T> DelayedSpSingleton<T>::GetInstance()
51 {
52     if (!instance_) {
53         std::lock_guard<std::mutex> lock(mutex_);
54         if (instance_ == nullptr) {
55             instance_ = new T();
56         }
57     }
58     return instance_;
59 }
60 
61 template<typename T>
DestroyInstance()62 void DelayedSpSingleton<T>::DestroyInstance()
63 {
64     std::lock_guard<std::mutex> lock(mutex_);
65     if (instance_) {
66         instance_.clear();
67         instance_ = nullptr;
68     }
69 }
70 } // namespace WorkScheduler
71 } // namespace OHOS
72 #endif // WORKSCHED_SP_SINGLETON_H