Browse Source

Increased multithreading security (#463)

* Increased multithreading security

* Uniform naming convention
xfmy 2 years ago
parent
commit
a5b374492a
1 changed files with 8 additions and 13 deletions
  1. 8 13
      cpputil/singleton.h

+ 8 - 13
cpputil/singleton.h

@@ -14,28 +14,23 @@
     private: \
         DISABLE_COPY(Class) \
         static Class* s_pInstance; \
+        static std::once_flag s_initFlag; \
         static std::mutex s_mutex;
 
 #define SINGLETON_IMPL(Class) \
     Class* Class::s_pInstance = NULL; \
+    std::once_flag Class::s_initFlag; \
     std::mutex Class::s_mutex; \
     Class* Class::instance() { \
-        if (s_pInstance == NULL) { \
-            s_mutex.lock(); \
-            if (s_pInstance == NULL) { \
-                s_pInstance = new Class; \
-            } \
-            s_mutex.unlock(); \
-        } \
-        return s_pInstance; \
+        std::call_once(s_initFlag, []() {s_pInstance = new Class;}); \
+	    return s_pInstance; \
     } \
     void Class::exitInstance() { \
-        s_mutex.lock(); \
-        if (s_pInstance) {  \
+        std::lock_guard<std::mutex> lock(s_mutex); \
+        if (s_pInstance) { \
             delete s_pInstance; \
-            s_pInstance = NULL; \
-        }   \
-        s_mutex.unlock(); \
+            s_pInstance = nullptr; \
+        } \
     }
 
 #endif // HV_SINGLETON_H_