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