设计模式之c++实现(一)

单例模式(多线程环境)

实验环境:Ubuntu14.04 多线程
单例模式实现的固定格式总结

1.避免第三方调用拷贝构造函数以及赋值操作符
2.避免第三方调用构造函数
3.避免第三方调用析构函数
4.总是需要一个静态方法用于全局访问

#ifndef __SINGLETON3_H_
#define __SINGLETON3_H_

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <boost/shared_ptr.hpp>

// __sync_val_compare_and_swap(&value_, 0, 0);
// __sync_fetcduih_and_add(&value_, x);
// __sync_lock_test_and_set(&value_, newValue);

template <class T> 
class Singleton3
{
public:
    //定义外部访问接口
    static boost::shared_ptr<T> GetInstance()
    {
        static int lock = 0;
        //原子操作
        if(__sync_val_compare_and_swap(&lock, 0, 1))
        {
            //实例化对象过程需要时间,为防止第一个线程未构造完成,后来的线程就使用对象
            while(lock != 2)
                ::sleep(0);
            return sp;
        }
        //实例对象用智能指针管理
        //第一个 GetInstance 的线程会实例化对象,往后的线程都不会执行到这步再实例化对象
        //shared_ptr释放对象时会掉用对象的析构函数,因此~Manager()必须是pubilc
        //但是这样做就没有禁止外部析构,因此定义一个删除器,shared_ptr释放对象时执行,
        //这样就可以将~Manager()定义为protected
        boost::shared_ptr<T> ptemp(new T(),T::deleter);
        sp = ptemp;
        lock = 2;//实例化完成标志
        printf("内存分配并初始化成员变量完成\n");
        return sp;
    }
protected:
    //禁用外部构造
    Singleton3()
    {
        printf("Singleton3 construct begin ...\n");
        ::sleep(3);//摸拟构造过程的时间
        printf("Singleton3 construct end ...\n");
    }
    //禁用外部析构
    ~Singleton3()
    {
        printf("Singleton3 destroy ...\n");
    }

public:
    //禁用赋值、拷贝
    Singleton3(const Singleton3& other) = delete;
    Singleton3& operator= (const Singleton3& right) = delete;

private:
    static boost::shared_ptr<T> sp;

    static void deleter(T* p) { delete p;}//定义删除器

/*   class Deleter
    {
        public:
            void operator()(T* p)
            {
                delete p;
            }
    };  */
};
template <class T>
boost::shared_ptr<T> Singleton3<T>::sp;//= NULL;


class Manager : public Singleton3<Manager>
{
    //Singleton3<Manager> 声明为友元,才能在new T()时访问Manager()
    friend class Singleton3<Manager>;
protected:
    //禁止外部构造
    Manager()
    {
        printf("Manager construct begin ...\n");
        ::sleep(2);//sleep(2)只是想模拟出构造过程需要时间
        count = 0;
        printf("Manager construct endl ...\n");
    }
    //禁止外部析构
     ~Manager()
    {
        printf("Manager destroy ...\n");
    } 
public:
    //删除拷贝、赋值
    Manager(const Manager& other) = delete;
    Manager& operator= (const Manager& right) = delete;

    void Print()
    {
        printf("count = %d\n",++count);
    }
private:
    int count;
};

#endif

该单例模式
通过模板和继承方式,获得了足够通用的能力
在创建单例实例的时候具有线程安全性
通过智能指针方式,防止内存泄露

测试代码

#include "singleton4.h"
#include <string.h>
#include <pthread.h>

void* thread_routine(void* args)
{
    printf("threadID:%lu...\n",pthread_self());
    Manager::GetInstance()->Print();
    return 0;
}

int main()
{   
    pthread_t tid[3] = {0};
    int ret;
    //创建三个线程
    for(int i = 0 ; i < 3 ; ++i)
    {
        if(ret = pthread_create(tid+i,NULL,thread_routine,NULL))
        {
            fprintf(stderr,"pthread_create error:%s\n",strerror(ret));
            exit(EXIT_FAILURE);
        }
    }
    for(int i= 0; i < 3 ; ++i)
        pthread_join(tid[i],NULL);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值