c语言多线程单例模式
2017-06-22 21:24
106 查看
c语言多线程单例模式
懒汉模式:
输出结果:
in thrFunc1
in thrFunc1
in mutex_init
address: 0x100300070
address: 0x100300070
饿汉模式:
输出结果:
address: 0x1003002e0
address: 0x1003002e0
懒汉模式:
#include <pthread.h> #include <stdio.h> pthread_once_t once = PTHREAD_ONCE_INIT; class Singleton { protected: static Singleton *_instance; static void mutex_init(void); //initialize mutex at beginning static pthread_mutex_t mutex; Singleton() {} public: static Singleton* getInstance(); }; Singleton* Singleton::_instance = NULL; pthread_mutex_t Singleton::mutex; void Singleton::mutex_init(void) { printf("in mutex_init\n"); pthread_mutex_init(&mutex, NULL); } Singleton* Singleton::getInstance() { pthread_once(&once, mutex_init); if(_instance == NULL) { pthread_mutex_lock(&mutex); if(_instance == NULL) _instance = new Singleton(); pthread_mutex_unlock(&mutex); } return _instance; } void* thrFunc1(void *arg) { printf("in thrFunc1\n"); auto p = Singleton::getInstance(); printf("address: %p\n", p); return NULL; } int main() { pthread_t pid1, pid2; pthread_create(&pid1, NULL, thrFunc1, NULL); pthread_create(&pid2, NULL, thrFunc1, NULL); pthread_join(pid1, NULL); pthread_join(pid2, NULL); }
输出结果:
in thrFunc1
in thrFunc1
in mutex_init
address: 0x100300070
address: 0x100300070
饿汉模式:
#include <stdio.h> #include <pthread.h> class Singleton { public: static Singleton* getInstance(); protected: Singleton() {}; static Singleton *_instance; }; Singleton* Singleton::_instance = new Singleton(); Singleton* Singleton::getInstance() { return _instance; } void* thrFunc1(void *arg) { auto p = Singleton::getInstance(); printf("address: %p\n", p); return NULL; } int main() { pthread_t pid1, pid2; pthread_create(&pid1, NULL, thrFunc1, NULL); pthread_create(&pid2, NULL, thrFunc1, NULL); pthread_join(pid1, NULL); pthread_join(pid2, NULL); }
输出结果:
address: 0x1003002e0
address: 0x1003002e0
相关文章推荐
- 好书整理系列之-设计模式:可复用面向对象软件的基础 9
- OpenSource产品的商业操作模式
- COM组件中的线程模式
- 打开你的 DMA 模式 (转)
- 水木-Emacs 的 texinfo 模式 (三)
- 水木-Emacs 的 texinfo 模式 (二)
- 水木-Emacs 的 texinfo 模式(一)
- 虚拟8086模式的内存管理
- 16位BIT模式下的ALPHA运算
- 简析J2EE应用程序数据库类设计模式
- 探讨对等网络(P2P)商务模式
- 让DMA66 硬盘工作在DMA33 模式
- 闲聊设计模式和类
- MFC,STL与设计模式?
- 好书整理系列之-设计模式:可复用面向对象软件的基础 8
- [导入]让DMA66 硬盘工作在DMA33 模式
- 好书整理系列之-设计模式:可复用面向对象软件的基础 7
- 好书整理系列之-设计模式:可复用面向对象软件的基础 6
- 好书整理系列之-设计模式:可复用面向对象软件的基础 5.5