学习一下C++的单例模式(Singleton)实现方法,顺便练习一下多线程编程。
代码:
1 #include <stdlib.h> 2 #include <windows.h> 3 4 /*** 5 * @author:zanzan101 6 */ 7 8 class A 9 { 10 public: 11 static A* get_instance() 12 { 13 while(WAIT_OBJECT_0 != WaitForSingleObject(mutex, 0)) 14 Sleep(100); // 设置100毫秒的相应时间 15 16 if(NULL == singleton) 17 singleton = new A(); 18 19 ReleaseMutex(mutex); 20 return singleton; 21 } 22 void do_something() 23 { 24 printf("The data is %d ", get_data()); 25 } 26 void set_data(const int& n) 27 { 28 data = n; 29 } 30 const int get_data() 31 { 32 return data; 33 } 34 protected: 35 private: 36 A():data(0){} 37 static A* singleton; 38 static HANDLE mutex; 39 int data; 40 }; 41 A* A::singleton = NULL; 42 HANDLE A::mutex = CreateMutex(NULL, NULL, "A"); 43 44 struct PARA 45 { 46 int a; 47 int b; 48 int c; 49 }; 50 void __stdcall runnable(PARA* para) 51 { 52 A* ptr = A::get_instance(); 53 54 // 下面这三个语句没用进行同步管理,可以从输出结果来感受多线程带来的混乱 55 ptr->set_data(para->a); 56 // 根据输出结果可知,printf不能被多线程中断,而cout可以被中断 57 printf("%d, %d, %d, %d ", para->a, para->b, para->c, ptr->get_data()); 58 ptr->do_something(); 59 } 60 61 // 关于C++的一种函数指针的类型转换:reinterpret_cast,高大上~ 62 typedef DWORD (__stdcall * func_callback)(void* para); 63 func_callback callback_func = reinterpret_cast<DWORD(__stdcall*)(void*)>(runnable); 64 65 int main() 66 { 67 // 关于单例模式 68 69 A* a = A::get_instance(); 70 a->set_data(10); 71 printf(">> 输出a: "); 72 a->do_something(); 73 A* b = A::get_instance(); 74 printf(">> 输出b: "); 75 b->do_something(); 76 b->set_data(20); 77 printf(">> 输出b: "); 78 b->do_something(); 79 b->set_data(20); 80 printf(">> 输出a: "); 81 a->do_something(); 82 83 if(a->get_data() == b->get_data()) 84 printf(">> a和b指向了同一个对象! "); 85 86 // 关于多线程 87 88 PARA para[10]; 89 for(int i = 0; i < 10; i++) 90 para[i].a = para[i].b = para[i].c = i; 91 92 HANDLE thread[10]; 93 for(int i = 0; i < 10; i++) 94 thread[i] = CreateThread(NULL, 1024, callback_func, (void*)¶[i], 0, 0); 95 96 Sleep(2000); 97 98 for(int i = 0; i < 10; i++) 99 { 100 TerminateThread(thread[i], 0); 101 CloseHandle(thread[i]); 102 } 103 104 system("pause"); 105 return 0; 106 }
输出结果:
>> 输出a: The data is 10 >> 输出b: The data is 10 >> 输出b: The data is 20 >> 输出a: The data is 20 >> a和b指向了同一个对象! 0, 0, 0, 0 1, 1, 1, 1 The data is 1 The data is 1 3, 3, 3, 3 The data is 2 4, 4, 4, 4 2, 2, 2, 2 5, 5, 5, 5 The data is 5 8, 8, 8, 8 6, 6, 6, 6 The data is 5 7, 7, 7, 7 The data is 5 9, 9, 9, 9 The data is 9 The data is 9 The data is 9 The data is 9 请按任意键继续. . .