单例模式中使用pthread_once 异常,求助
/*
#ifndef SINGLETON_H_
#define SINGLETON_H_
#include <pthread.h>
class Singleton {
public:
static Singleton * getInstance() {
if (instance == NULL) {
pthread_once(&once, once_init);
//pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);
if (instance == NULL)
instance = new Singleton();
pthread_mutex_unlock(&mutex);
}
return instance;
}
private:
Singleton() {
}
~Singleton();
Singleton(const Singleton &s);
static void once_init(void) {
pthread_mutex_init(&mutex, NULL);
}
static Singleton *instance;
static pthread_mutex_t mutex;
static pthread_once_t once;
};
pthread_once_t Singleton::once = PTHREAD_ONCE_INIT;
pthread_mutex_t Singleton::mutex;
Singleton *Singleton::instance = NULL;
#endif /* SINGLETON_H_ */
相关推荐
[并发并行]_[线程同步]_[pthread_once 实现单例模式分析]
http://blog.csdn.net/infoworld/article/details/49798215 mingw 编译,Win32部分可以直接用vs编译.
Linux线程之一次性初始化(pthread_once)
1.一次性初始化 在 Linux函数列表 中描述了Linux线程中的常用函数,这里详细讲解 pthread_once 函数的功能和使用。 (1)为何有“一次性初始化概念”出现? 其实在开发中,很多事情都仅仅需要做一次,不管是什么。在主函数中并且在调用任何其他依赖于初始化的事物之前初始化应用是最为容易的,特别是在创建任何线程之前初始化它需要的数据,如 互斥量、条件变量、线程特定数据键等。 ...
linux创建线程之pthread_create的具体使用
pthread_create函数 函数简介 pthread_create是UNIX环境创建线程函数 头文件 #include 函数声明 int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg); 返回值 若成功则返回0,否则返回出错编号 参数 第一个参数为指向线程标识符的指针。 第二个参数用来设置线程属性。 第三个参数是线程运行函数的地址。 最后一个参
老生常谈C++的单例模式与线程安全单例模式(懒汉/饿汉)
下面小编就为大家带来一篇老生常谈C++的单例模式与线程安全单例模式(懒汉/饿汉)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
C++单例模式实现[项目源码]
本文详细介绍了C++中单例模式的多种实现方法。单例模式确保一个类只有一个实例,并提供全局访问点。文章首先介绍了初始版本的手动创建和释放方法,指出了其内存泄漏的风险。接着,引入了RAII(Resource Acquisition Is Initialization)思想,通过对象的生命周期管理资源,实现自动释放。文章还探讨了嵌套类和atexit函数的使用,进一步优化资源管理。最后,针对多线程环境下的线程安全问题,提出了使用pthread_once和atexit的组合方案,确保初始化代码只执行一次。这些方法为开发者提供了灵活且安全的单例模式实现选择。


