面试题2:实现Singleton模式

题目:设计一个类,我们只能生成该类的一个实例

分析

Singleton即单例模式。既然题目要求只能生成类的一个实例,那我们必须把类的构造函数和拷贝构造函数设置为private以阻止类的调用者随意创建对象。

我们来看代码


//单例模式类包含的数据
typedef struct data{
    int a;
    //other
}data;

class singleton{
public:
    data* create(int x)
    {
        if(instance==NULL)
        {
            instance=new data;
            instance->a=x;
            //DoOtherThing
        }
        return instance;
    }
    ~singleton()
    {
        if(instance!=NULL)
        {
            delete instance;
        }
    }
private:
    singleton()
    {}
    singleton(const singleton& s)
    {}

private:
    static data* instance;
};
data* singleton::instance=NULL;

上面的代码可以在单线程环境下顺利运行。但在多线程环境中,如果两个线程同时执行create函数中的if语句,则以下这种情况是可能发生的:

线程1线程2
if(instance==NULL) 成立
if(instance==NULL)成立
instance=new data;生成对象
instance=new data;原来的instance指向的内存丢失

由此可见,如果直接以上面的代码在多线程环境下跑时,会有内存泄露的问题。

解决办法就是Linux下的pthread锁机制。


//同步锁,防止了在多线程程序中可能出现的问题
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;

class singleton{
public:
    data* create(int x)
    {
        pthread_mutex_lock(&lock);
        if(instance==NULL)
        {
            instance=new data;
            instance->a=x;
            //DoOtherThing
        }
        pthread_mutex_unlock(&lock);
        return instance;
    }
    ~singleton()
    {
        if(instance!=NULL)
        {
            delete instance;
        }
    }
private:
    singleton()
    {}
    singleton(const singleton& s)
    {}

private:
    static data* instance;
};
data* singleton::instance=NULL;

恩,我们来看看还有没有可以优化的地方。

因为加锁是一个很耗时的操作,频繁的加锁解锁会导致程序性能下降。上面的代码只有在第一次调用create函数时的加锁操作才是必要且有效的。所以我们在加锁前先判断一下,如果实例已经被创建,则跳过锁操作。

create函数代码:

data* create(int x)
{
    if(instance==NULL)
    {
        pthread_mutex_lock(&lock);
        if(instance==NULL)
        {
            instance=new data;
            instance->a=x;
            //DoOtherThing
        }
        pthread_mutex_unlock(&lock);
    }
    return instance;
}
以上

如果有任何不足,欢迎指正!
完整代码和测试用例在github上:点我前往

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值