• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2020 The Libphonenumber Authors
2 //
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 I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_STDMUTEX_H_
16 #define I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_STDMUTEX_H_
17 
18 #include <mutex>
19 
20 #include "phonenumbers/base/basictypes.h"
21 
22 namespace i18n {
23 namespace phonenumbers {
24 
25 template <class T>
26 class Singleton {
27  public:
Singleton()28   Singleton() {}
~Singleton()29   virtual ~Singleton() {}
30 
GetInstance()31   static T* GetInstance() {
32     if (once_init_) {
33       singleton_mutex_.lock();
34       if (once_init_) {
35         Init();
36         once_init_ = false;
37       }
38       singleton_mutex_.unlock();
39     }
40     return instance_;
41   }
42 
43  private:
44   DISALLOW_COPY_AND_ASSIGN(Singleton);
45 
Init()46   static void Init() {
47     instance_ = new T();
48   }
49 
50   static T* instance_;  // Leaky singleton.
51   static std::mutex singleton_mutex_;
52   static bool once_init_;
53 };
54 
55 template <class T> T* Singleton<T>::instance_;
56 template <class T> std::mutex Singleton<T>::singleton_mutex_;
57 template <class T> bool Singleton<T>::once_init_ = true;
58 
59 }  // namespace phonenumbers
60 }  // namespace i18n
61 
62 #endif  // I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_STDMUTEX_H_
63