Continued ripping up the source.
[aesalon.git] / monitor / src / misc / Singleton.h
blob690f4a0e41f78f317ce1845fa2e9f3429c03b13e
1 #ifndef AESALON_MISC_SINGLETON_H
2 #define AESALON_MISC_SINGLETON_H
4 #include <pthread.h>
6 #include "Exception.h"
8 namespace Aesalon {
9 namespace Misc {
11 /** Exception class, thrown when a singleton is initialized for the second
12 time.
14 class MultipleSingletonException : public Exception {
15 public:
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 {
23 public:
24 UnitializedSingletonException() : Exception("Singleton not initialized") {}
27 /** Singleton class, contains a basic singleton implementation. */
28 template<typename Type>
29 class Singleton {
30 private:
31 /** Singleton instance, declared in each singleton derived class. */
32 static Type *instance;
33 /** Singleton multithreading mutex. Makes the singleton class
34 thread-safe. */
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
39 thread-safe.
41 pthread_mutex_t *get_mutex() { return &singleton_mutex; }
42 public:
43 /** Basic constructor, checks if the singleton has been initialized yet.
44 @throw MultipleSingletonException If the singleton has already been
45 initialized.
47 Singleton() {
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();
67 return instance;
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());
79 } // namespace Misc
80 } // namespace Aesalon
82 #endif