1 #ifndef AESALON_MISC_SINGLETON_H
2 #define AESALON_MISC_SINGLETON_H
11 /** Exception class, thrown when a singleton is initialized for the second
14 class MultipleSingletonException
: public Exception
{
16 MultipleSingletonException() : Exception("Singleton already initialized") {}
19 /** Exception class, thrown when a singleton instance is requested before the
20 singleton has been initialized.
22 class UnitializedSingletonException
: public Exception
{
24 UnitializedSingletonException() : Exception("Singleton not initialized") {}
27 /** Singleton class, contains a basic singleton implementation. */
28 template<typename Type
>
31 /** Singleton instance, declared in each singleton derived class. */
32 static Type
*instance
;
33 /** Singleton multithreading mutex. Makes the singleton class
35 pthread_mutex_t singleton_mutex
;
37 /** Returns the lockable mutex for the current singleton.
38 @return A lockable mutex, which helps make the singleton library
41 pthread_mutex_t
*get_mutex() { return &singleton_mutex
; }
43 /** Basic constructor, checks if the singleton has been initialized yet.
44 @throw MultipleSingletonException If the singleton has already been
48 if(instance
) throw MultipleSingletonException();
49 instance
= static_cast<Type
*>(this);
50 pthread_mutex_init(&singleton_mutex
, NULL
);
53 /** Virtual destructor. If the instance is initialized, set the pointer to
54 zero, so that it can be initialized again if nessasary.
56 virtual ~Singleton() {
57 if(instance
) instance
= 0;
58 pthread_mutex_destroy(&singleton_mutex
);
61 /** Static member to return the singleton instance.
62 @throw UnitializedSingletonException If the instance is not initialized.
63 @return The singleton instance, as a pointer.
65 static Type
*get_instance() {
66 if(!instance
) throw UnitializedSingletonException();
70 static void lock_mutex() {
71 pthread_mutex_lock(get_instance()->get_mutex());
74 static void unlock_mutex() {
75 pthread_mutex_unlock(get_instance()->get_mutex());
80 } // namespace Aesalon