一、线程安全性的讲解
1、视频截图
2、线程安全性的代码
加不加临界区进行验证
1 //!!!!!!!!! 加C++泛型编程与STL开发实战 QQ群:726114806下载代码和交流 2 #include <afxwin.h> 3 #include <iostream> 4 #include <stdio.h> 5 using namespace std; 6 7 CRITICAL_SECTION g_cs; 8 class Singleton { 9 private: 10 Singleton() { 11 m_singer = NULL; 12 cout << "构造一个Singleton对象" << endl; 13 } 14 public: 15 static Singleton* getInstance() { //懒汉式:延迟加载 16 if (m_singer == NULL) { 17 ::EnterCriticalSection(&g_cs); 18 if(m_singer == NULL) 19 m_singer = new Singleton; 20 ::LeaveCriticalSection(&g_cs); 21 } 22 return m_singer; 23 } 24 private: 25 static Singleton* m_singer; 26 }; 27 28 UINT Func(LPVOID) { 29 printf("%x\n", Singleton::getInstance()); 30 return 0; 31 } 32 Singleton *Singleton::m_singer = NULL;//new Singleton; 在C++中构造函数不是线程安全的 33 int main(void) { 34 //Singleton *p = new Singleton; 35 /*Singleton* p1 = Singleton::getInstance(); 36 Singleton* p2 = Singleton::getInstance(); 37 printf("p1=%x,p2=%x", p1, p2);*/ 38 ::InitializeCriticalSection(&g_cs); 39 for (int i = 0;i < 10;i++) { 40 AfxBeginThread(Func, NULL); 41 } 42 ::DeleteCriticalSection(&g_cs); 43 system("pause"); 44 return 0; 45 }验证代码
标签:Singleton,代码,模式,线程,单例,include,安全性 From: https://www.cnblogs.com/zeliangzhang/p/17361025.html