单例模式多线程安全实现

#include<pthread.h>
template<typename T>
class Singleton

{

public:
    static T& instance()
    {
        pthread_once(&ponce_, &Singleton::init);
        return *value_;
    }

private:
   Singleton();
    ~Singleton();
    static void init()
    {
        value_= new T();
    }
    private:
    static pthread_once_t ponce_;
    static T* value_;
};

template<typename T>
pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT;
template<typename T>
T* Singleton<T>::value_ = NULL;

#include<iostream>
using namespace std;
class A
{
public:
	A()
	{
		cout << "A" << endl;
	}
};
class B
{
public:
        B()
        {
                cout << "B" << endl;
        }
};
int main()
{
	A& a =  Singleton<A>::instance();
	A& b =  Singleton<A>::instance();
 	B& c =  Singleton<B>::instance();
	return 0;

}
发布了150 篇原创文章 · 获赞 79 · 访问量 63万+

猜你喜欢

转载自blog.csdn.net/liu0808/article/details/87968481