当前位置:网站首页>Thread safe sigleton (singleton mode)

Thread safe sigleton (singleton mode)

2022-04-23 20:59:00 Descosmos

The singleton pattern

The definition of singleton pattern and its most basic implementation will not be mentioned more , It's important to point out that , For general singleton mode , On the basis of if(hold_ == NULL) It is obviously difficult to meet the requirements of thread safety , Therefore, this article through pthread_once To achieve .

Be careful , You can also use thread synchronization mechanism , Like locks , Semaphore, etc .

template<typename T>
class Signleton: boost noncopyable{
    
public:
	static T& instance(){
    
		pthead_once(&ponce_, &Signleton::init);
		return *value_;
	}

private:
	//  Set constructors and destructors to private,  So that singleton mode cannot be created on the stack 
	Signleton();
	~Signleton();
	
	static void init(){
    
		value_ = new T();
	}

private:
	static pthread_once_t ponce_;
	static T* value_;	//  Data in singleton mode 
};

//  Must be defined in the header file static  Variable 
pthread_once_t Signleton<T>::ponce_ = PTHREAD_ONCE_INIT;

template<typename T>
T* Signleton<T>::value_ NULL;

Usage method

Foo &foo = Sigleton<Foo>::instance();

Be careful

This singleton pattern does not consider how to destroy objects .

版权声明
本文为[Descosmos]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210545298121.html