Http://buptdtt.blog.51cto.com/2369962/975101
- // Singleton. h
- # Ifndef _ singleton_h _
- # DEFINE _ singleton_h _
- # Include <iostream>
- # Include <pthread. h>
- Using namespace STD;
-
- Class locker
- {
- Public:
- Inline locker () {pthread_mutex_init (& mutex, null );}
- Inline ~ Locker () {pthread_mutex_destroy (& mutex );}
- Inline void lock () {pthread_mutex_lock (& mutex );}
- Inline void unlock () {pthread_mutex_unlock (& mutex );}
- PRIVATE:
- Pthread_mutex_t mutex;
- };
- Class Singleton
- {
- Public:
- Static Singleton * instance ();
-
- PRIVATE:
- Singleton ();
- Static Singleton * m_pinstance;
- Class Garbo // Delete the singleton Instance Object
- {
- Public:
- ~ Garbo ()
- {
- If (singleton: m_pinstance)
- {
- Delete singleton: m_pinstance;
- }
- }
- };
- Static Garbo GB; // At the end of the program, the system will call its destructor
-
- };
- # Endif //~ _ Singleton_h _
-
-
-
-
- // Singleton. cpp
- # Include "Singleton. H"
- # Include <iostream>
- Using namespace STD;
-
-
- Singleton * singleton: m_pinstance = 0;
- Singleton: Singleton ()
- {
- Cout <"Singleton..." <Endl;
- }
- Singleton * singleton: instance ()
- {
- If (null = m_pinstance)
- {
- Locker llock;
- Llock. Lock ();
- If (null = m_pinstance)
- {
- M_pinstance = new Singleton ();
- }
- Llock. Unlock ();
- }
- Return m_pinstance;
-
- }
-
- // Main. cpp
- # Include "Singleton. H"
- # Include <iostream>
- Using namespace STD;
- Int main (INT argc, char * argv [])
- {
- Singleton * SGN = singleton: instance ();
- Return 0;
- }
- Declare the constructor as private to prevent it from being instantiated. Use a static member variable and a static function to construct a unique object. New Space is added to static functions. Therefore, the built-in destructor of member objects are used to release the memory. To ensure multi-threaded security, lock objects before they are created, and then unlock objects after they are created.