From 44592ef1ad56cec24ae173fa46a78bd2b8cd66c8 Mon Sep 17 00:00:00 2001 From: xfmy <2773329846@qq.com> Date: Sun, 19 Nov 2023 16:30:23 +0800 Subject: [PATCH 1/2] Increased multithreading security --- cpputil/singleton.h | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/cpputil/singleton.h b/cpputil/singleton.h index 9553b017f..c08ae87cc 100644 --- a/cpputil/singleton.h +++ b/cpputil/singleton.h @@ -14,28 +14,23 @@ private: \ DISABLE_COPY(Class) \ static Class* s_pInstance; \ + static std::once_flag initFlag; \ static std::mutex s_mutex; #define SINGLETON_IMPL(Class) \ Class* Class::s_pInstance = NULL; \ + std::once_flag Class::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(initFlag, []() {s_pInstance = new Class;}); \ + return s_pInstance; \ } \ void Class::exitInstance() { \ - s_mutex.lock(); \ - if (s_pInstance) { \ + std::lock_guard lock(s_mutex); \ + if (s_pInstance) { \ delete s_pInstance; \ - s_pInstance = NULL; \ - } \ - s_mutex.unlock(); \ + s_pInstance = nullptr; \ + } \ } #endif // HV_SINGLETON_H_ From bc3ca5277cdd2e78e81e34925b8ccef747451398 Mon Sep 17 00:00:00 2001 From: xfmy <2773329846@qq.com> Date: Mon, 20 Nov 2023 11:21:03 +0800 Subject: [PATCH 2/2] Uniform naming convention --- cpputil/singleton.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cpputil/singleton.h b/cpputil/singleton.h index c08ae87cc..ff78af616 100644 --- a/cpputil/singleton.h +++ b/cpputil/singleton.h @@ -14,15 +14,15 @@ private: \ DISABLE_COPY(Class) \ static Class* s_pInstance; \ - static std::once_flag initFlag; \ + static std::once_flag s_initFlag; \ static std::mutex s_mutex; #define SINGLETON_IMPL(Class) \ Class* Class::s_pInstance = NULL; \ - std::once_flag Class::initFlag; \ + std::once_flag Class::s_initFlag; \ std::mutex Class::s_mutex; \ Class* Class::instance() { \ - std::call_once(initFlag, []() {s_pInstance = new Class;}); \ + std::call_once(s_initFlag, []() {s_pInstance = new Class;}); \ return s_pInstance; \ } \ void Class::exitInstance() { \