/*MT* MediaTomb - http://www.mediatomb.cc/ singleton.h - this file is part of MediaTomb. Copyright (C) 2005 Gena Batyan , Sergey 'Jin' Bostandzhyan Copyright (C) 2006-2007 Gena Batyan , Sergey 'Jin' Bostandzhyan , Leonhard Wimmer MediaTomb is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. MediaTomb is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License version 2 along with MediaTomb; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. $Id: singleton.h 1124 2007-02-17 21:49:15Z lww $ */ /// \file singleton.h #ifndef __SINGLETON_H__ #define __SINGLETON_H__ #include "sync.h" #include "zmmf/zmmf.h" #define SINGLETON_CUR_MAX 10 template class Singleton; class SingletonManager : public zmm::Object { public: static zmm::Ref getInstance(); SingletonManager(); void registerSingleton(zmm::Ref > object); virtual void shutdown(bool complete = false); protected: static zmm::Ref instance; static zmm::Ref mutex; zmm::Ref > > singletonStack; }; template class Singleton : public zmm::Object { public: static zmm::Ref getInstance() { if (! singletonActive) throw _Exception(_("singleton is currently inactive!")); if (instance == nil) { AUTOLOCK(mutex); if (! singletonActive) throw _Exception(_("singleton is currently inactive!")); if (instance == nil) // check again, because there is a very small chance // that 2 threads tried to lock() concurrently { zmm::Ref tmpInstance = zmm::Ref(new T()); tmpInstance->registerSingleton(); tmpInstance->init(); instance = tmpInstance; } } return instance; } protected: virtual ~Singleton() { } virtual void init() { } virtual void shutdown() { } static zmm::Ref mutex; static zmm::Ref instance; static bool singletonActive; virtual void registerSingleton() { SingletonManager::getInstance()->registerSingleton(zmm::Ref >((Singleton *)this)); } private: virtual void inactivateSingleton() { //log_debug("%d %d\n", singletonActive, instance.getPtr()); singletonActive = false; instance = nil; } virtual void reactivateSingleton() { singletonActive = true; } friend class SingletonManager; }; #define SINGLETON_MUTEX(klass, recursive) template <> zmm::Ref Singleton::mutex = zmm::Ref(new Mutex(recursive)) //template zmm::Ref Singleton::mutex = zmm::Ref(new Mutex()); template zmm::Ref Singleton::instance = nil; template bool Singleton::singletonActive = true; #endif // __SINGLETON_H__