java的单例模式可以通过内部类来保证线程安全,C++的代码很多时候(muduo里边在linux下可以使用pthread_once)单例模式还是双判断加锁,信号量也可以实现锁的功能,就当练习一下信号量的使用了
#include <pthread.h>
#include <semaphore.h>
class Singleton
{
private:
Singleton(){}
static Singleton *p;
public:
static sem_t sem;
static int index;
static Singleton* getInstance()
{
if (p == NULL)
{
if (sem_wait(&sem) == 0)
{
if (p == NULL)
{
p = new Singleton();
}
sem_post(&sem);
}
}
return p;
}
static void destroy()
{
if (NULL != p)
{
delete p;
p = NULL;
}
sem_destroy(&sem);
}
};
sem_t Singleton::sem;
int Singleton::index = sem_init(&Singleton::sem,0,1);
Singleton* Singleton::p = NULL;