博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一种线程安全的单例模式实现
阅读量:6940 次
发布时间:2019-06-27

本文共 1604 字,大约阅读时间需要 5 分钟。

#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; }

转载地址:http://ihnnl.baihongyu.com/

你可能感兴趣的文章
String StringBuilder StringBuffer
查看>>
安装 ruby, sass 和 compass
查看>>
linux系统故障排除
查看>>
Python黑魔法:元类
查看>>
jQuery.extend()和 jQuery.fn.extend()用法总结
查看>>
Centos 7 学习安装步骤
查看>>
Linux常用命令简介
查看>>
2. 性能测试中常见术语集合
查看>>
内存rank概念和区分
查看>>
c++解惑之读取文件getline
查看>>
Spell Checker - 新版Chrome的纠错特性
查看>>
http协议以及httpd2.2与httpd2.4的详解
查看>>
jpa postgresql 使用uuid作为主键
查看>>
Linux文件目录
查看>>
8.1 shell介绍 8.2 命令历史 8.3 命令补全和别名 8.4 通配符 8.5 输入输出重
查看>>
GAEPhotos V1.02 发布了
查看>>
docker 部署Tomcat应用相关操作
查看>>
文件权限
查看>>
回顾2017,展望2018
查看>>
Eclipse 编译运行卡顿
查看>>