• 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_WIN32_H_
16 #define I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_WIN32_H_
17 
18 #include <windows.h>
19 #include <synchapi.h>
20 
21 #include "phonenumbers/base/basictypes.h"
22 
23 namespace i18n {
24 namespace phonenumbers {
25 
26 template <class T>
27 class Singleton {
28  public:
Singleton()29   Singleton() {}
~Singleton()30   virtual ~Singleton() {}
31 
GetInstance()32   static T* GetInstance() {
33     if (once_init_) {
34       EnterCriticalSection(&critical_section_);
35       if (once_init_) {
36         Init();
37         once_init_ = false;
38       }
39       LeaveCriticalSection(&critical_section_);
40     }
41     return instance_;
42   }
43 
44  private:
45   DISALLOW_COPY_AND_ASSIGN(Singleton);
46 
Init()47   static void Init() {
48     instance_ = new T();
49   }
50 
51   static T* instance_;  // Leaky singleton.
52   static CRITICAL_SECTION critical_section_;
53   static bool once_init_;
54 };
55 
perform_init_crit(CRITICAL_SECTION & cs)56 static bool perform_init_crit(CRITICAL_SECTION& cs)
57 {
58   InitializeCriticalSection(&cs);
59   return true;
60 }
61 
62 template <class T> T* Singleton<T>::instance_;
63 template <class T> CRITICAL_SECTION Singleton<T>::critical_section_;
64 template <class T> bool Singleton<T>::once_init_=perform_init_crit(Singleton<T>::critical_section_);
65 
66 }  // namespace phonenumbers
67 }  // namespace i18n
68 
69 #endif  // I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_WIN32_H_
70