单例模式多线程安全实现

#include
template
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
pthread_once_t Singleton::ponce_ = PTHREAD_ONCE_INIT;
template
T* Singleton::value_ = NULL;

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

}

 

你可能感兴趣的:(c++)