- #include <iostream>
- #include <cstdio>
- #include <Windows.h>
- class TestClass
- {
- public:
- TestClass()
- :x(0)
- {
- ::Sleep(1000);
- num++;
- }
- ~TestClass(){}
- void Inc() { x++;}
- void Show()
- {
- char result[20] ={0};
- sprintf(result, "x = %d\n", x);
- printf(result);
- }
- public:
- static int num;
- private:
- int x;
-
- };
- int TestClass::num = 0;
- class CLock
- {
- public:
- CLock()
- {
- ::InitializeCriticalSection(&m_Section);
- }
- ~CLock()
- {
- ::DeleteCriticalSection(&m_Section);
- }
- void Lock()
- {
- ::EnterCriticalSection(&m_Section);
- }
- void UnLock()
- {
- ::LeaveCriticalSection(&m_Section);
- }
- private:
- CRITICAL_SECTION m_Section;
- };
- template <typename T>
- class Singleton
- {
- public:
- static T* getPointer()
- {
- if(m_instance == NULL)
- {
- m_Lock.Lock();
- if(m_instance == NULL)
- {
- T* instance = new T();
- m_instance = reinterpret_cast<void*>(instance);
- }
- m_Lock.UnLock();
- }
- return reinterpret_cast<T*>(m_instance);
-
- }
- static T & instance()
- {
- return *getPointer();
- }
- static void release()
- {
- if(m_instance)
- {
- delete m_instance;
- m_instance = NULL;
- }
- }
- private:
- static void* m_instance;
- static CLock m_Lock;
- };
- template<typename T>
- void* Singleton<T>::m_instance = 0;
- template<typename T>
- CLock Singleton<T>::m_Lock;
- HANDLE g_hThreads[3] = {0};
- DWORD WINAPI func(LPVOID p)
- {
-
- int i = 0;
- while(i < 5)
- {
- Singleton<TestClass>::instance().Inc();
- Singleton<TestClass>::instance().Show();
- Sleep(1);
- ++i;
- }
- return 1;
- }
- int main()
- {
- for(int i = 0; i < 3; ++i)
- {
- g_hThreads[i] = ::CreateThread(NULL, 0, func, NULL, 0, NULL);
- }
- ::WaitForMultipleObjects(3, g_hThreads, TRUE, INFINITE );
- Singleton<TestClass>::release();
- std::cout << "finished" << std::endl;
- std::cout << "has create " << TestClass::num << " TestClass!" << std::endl;
- system("pause");
- return 0;
- }
程序运行结果
x = 1
x = 2
x = 3
x = 4
x = 5
x = 6
x = 7
x = 9
x = 8
x = 10
x = 12
x = 11
x = 13
x = 14
x = 15
finished
has create 1 TestClass!
阅读(4155) | 评论(0) | 转发(0) |