c语言多线程单例模式
来源:互联网 发布:mac页面比例缩小快捷键 编辑:程序博客网 时间:2024/05/18 18:17
c语言多线程单例模式
懒汉模式:
#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
阅读全文
0 0
- c语言多线程单例模式
- objective c - 单例模式(多线程)
- 单例模式 (C语言实现)
- Objective-c语言_单例模式
- 多线程单例模式
- C语言单件模式
- C语言和设计模式(之单例模式)
- 单例模式-多线程单例模式
- 单例模式的多线程安全支持(C++)
- C语言设计模式:单件模式
- Java, C#, JavaScript三种语言实现单例模式
- 单例模式 c语言的实现和使用
- IOS-3-Objective-C语言:单例设计模式
- 【C#】高级语言特有的单例模式
- Objective-C语言——单例模式
- 【C#】高级语言特有的单例模式
- 单例模式与多线程
- 懒汉 多线程 单例模式
- 项目实训第四周
- POJ 1815 Friendship 笔记
- 011. Spring Bean单例与非单例
- usb之枚举
- 笔试错题集锦
- c语言多线程单例模式
- Loj-110乘法逆元(线性模板题)
- 表、栈和队列
- ubuntu 16.4安装后无法在win7里拖动和复制文本和文件的解决方法
- Python3-Flask-微信公众号开发
- CSDN机器学习笔记十一 k-近邻算法
- 《Advanced Bash-scripting Guide》学习(三):自删除脚本和自读取内容的脚本
- Linux C 套接字socket UDP
- windows下安装mongodb