一种线程安全的单例模式实现
2012-04-19 00:25
330 查看
#include <iostream> #include <vector> #include <bitset> #include <assert.h> #include <Windows.h> #include <process.h> using namespace std; class CSingleton { private: class CAssistForSingleton { private: CRITICAL_SECTION m_cs; public: CAssistForSingleton() { InitializeCriticalSection(&m_cs); } ~CAssistForSingleton() { DeleteCriticalSection(&m_cs); } public: void Lock() { EnterCriticalSection(&m_cs); } void UnLock() { LeaveCriticalSection(&m_cs); } }; private: static CAssistForSingleton m_refSycObj; static CSingleton *m_pInstance; static int m_nData; private: CSingleton() { } public: static CSingleton *GetInstatnce() { m_refSycObj.Lock(); if (NULL == m_pInstance) { m_pInstance = new CSingleton; cout<<"new CSingleton"<<endl; } m_refSycObj.UnLock(); return m_pInstance; } public: static int GetData() { return m_nData; } static void SetData(int nData) { m_refSycObj.Lock(); m_nData = nData; m_refSycObj.UnLock(); } }; CSingleton::CAssistForSingleton CSingleton::m_refSycObj = CSingleton::CAssistForSingleton(); CSingleton *CSingleton::m_pInstance = NULL; int CSingleton::m_nData = 0; unsigned int WINAPI ThreadFun(void *) { cout<<"Launcher Thread"<<endl; for(int i = 0 ; i < 99999999 ; i++) { CSingleton *pSingl = CSingleton::GetInstatnce(); if (NULL != pSingl) { pSingl->SetData(i); } Sleep(500); } return 0; } int main(int argv, char *argc[]) { uintptr_t HandleThread[10]; unsigned int nThreadId = 0; for(int i = 0 ; i < 10 ; i++) { HandleThread[i] = _beginthreadex(NULL, 0, ThreadFun, NULL, 0, &nThreadId); } WaitForMultipleObjects(10, (const HANDLE *)HandleThread, TRUE, INFINITE); return 0; }
相关文章推荐
- 一种线程安全的单例模式实现
- Java基础学习总结(85)——Java中四种线程安全的单例模式实现方式
- 真正的创新必然是基于对市场的了解,对客户反馈的观察,开发出来的产品一定要适应市场,提出的模式一定要能解决现实的问题。而在这其中,技术只是一种实现手段。
- 经典的一种观察者模式实现
- 自编监听器的一种实现模式
- B/S 模式 套打 的一种实现方式<转>
- C# 数据库连接池 线程安全 单例模式 的实现
- 生产者和消费的模式的一种实现
- 用C++实现单例模式2——线程安全
- 一种互联网应用的分布式架构模式微服务应用框架的实现(gradle,dubbo,zookeeper,springmmvc)
- 实现singleton模式(设计模式的一种)
- 实现一个单例模式的类,要求线程安全
- 一种夜间模式简单实现方案
- B/S 模式 套打 的一种实现方式
- 线程安全单例模式几种优雅的实现
- 一种线程安全的单例模式(10.4.1更新)
- 单例模式——C++实现线程安全的单例
- 单例模式——C++实现线程安全的单例
- 转 一种线程安全的单例模式
- Java基于解释器模式实现定义一种简单的语言功能示例