From 5c989b9d7f701635fb6f45397f563d63a2d5b302 Mon Sep 17 00:00:00 2001 From: Julien Michel <julien.michel@cnes.fr> Date: Mon, 12 Mar 2018 10:42:14 +0100 Subject: [PATCH] ENH: Refactor singleton pattern to be thread-safe and simpler --- Modules/Core/Common/include/otbLogger.h | 2 +- Modules/Core/Common/src/otbLogger.cxx | 33 ++++++++++++++----------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/Modules/Core/Common/include/otbLogger.h b/Modules/Core/Common/include/otbLogger.h index d61c22bf4a..3e69d173c0 100644 --- a/Modules/Core/Common/include/otbLogger.h +++ b/Modules/Core/Common/include/otbLogger.h @@ -61,7 +61,7 @@ private: Logger(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented - static Pointer Singleton; + static Pointer CreateInstance(); }; // class Logger diff --git a/Modules/Core/Common/src/otbLogger.cxx b/Modules/Core/Common/src/otbLogger.cxx index 37a2ef0540..b3730cf445 100644 --- a/Modules/Core/Common/src/otbLogger.cxx +++ b/Modules/Core/Common/src/otbLogger.cxx @@ -29,25 +29,28 @@ namespace otb { -Logger::Pointer Logger::Singleton = ITK_NULLPTR; - -Logger::Pointer Logger::Instance() +Logger::Pointer Logger::CreateInstance() { - if(!Logger::Singleton) - { - Logger::Singleton = Logger::New(); + Logger::Pointer instance = Logger::New(); - // By default, redirect logs to std::cout - itk::StdStreamLogOutput::Pointer defaultOutput = itk::StdStreamLogOutput::New(); - defaultOutput->SetStream(std::cout); + // By default, redirect logs to std::cout + itk::StdStreamLogOutput::Pointer defaultOutput = itk::StdStreamLogOutput::New(); + defaultOutput->SetStream(std::cout); + + instance->AddLogOutput(defaultOutput); + + // Log setup information + instance->LogSetupInformation(); - Logger::Singleton->AddLogOutput(defaultOutput); + return instance; +} - // Log setup information - Logger::Singleton->LogSetupInformation(); - } - - return Logger::Singleton; +Logger::Pointer Logger::Instance() +{ + // Static locales are initialized once in a thread-safe way + static Logger::Pointer instance = CreateInstance(); + + return instance; } Logger::Logger() -- GitLab