- #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;
- template <typename T>
- class Singleton
- {
- public:
- static T* getPointer()
- {
- static volatile long beingCreated = false;
- if(m_instance != 0)
- {
- return reinterpret_cast<T*>(m_instance);
- }
- if(!InterlockedExchange(&beingCreated, true))
- {
- T* instance = new T();
- m_instance = reinterpret_cast<void*>(instance);
- InterlockedExchange(&beingCreated, false);
- return instance;
- }
- while(true)
- {
- if(!beingCreated)
- {
- return reinterpret_cast<T*>(m_instance);
- }
- Sleep(0);
- }
-
- }
- static T & instance()
- {
- return *getPointer();
- }
- static void release()
- {
- if(m_instance)
- {
- delete m_instance;
- m_instance = NULL;
- }
- }
- private:
- static void* m_instance;
- };
- template<typename T>
- void* Singleton<T>::m_instance = 0;
- 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 Object!" << std::endl;
- system("pause");
- return 0;
- }
程序运行结果:
x = 2
x = 1
x = 3
x = 4
x = 5
x = 6
x = 8
x = 9
x = 7
x = 10
x = 11
x = 12
x = 13
x = 14
x = 15
finished
has create 1 TestClass Object!
最后x = 15, 并且只创建了一个TestClass Object.
倘若将static T* getPointer()改为
- static T* getPointer()
- {
- static volatile long beingCreated = false;
- if(m_instance != 0)
- {
- return reinterpret_cast<T*>(m_instance);
- }
- T* instance = new T();
- m_instance = reinterpret_cast<void*>(instance);
- return instance;
- }
则程序运行结果为
x = 1
x = 1
x = 1
x = 3
x = 4
x = 2
x = 5
x = 7
x = 7
x = 8
x = 9
x = 10
x = 11
x = 13
x = 12
finished
has create 3 TestClass Object!
最后的x = 12, 并且创建了3个 TestClass Object,线程不安全,并且违背了单一原则
阅读(2268) | 评论(0) | 转发(0) |