Singleton design pattern (Singleton) C ++ to achieve

Singleton - effect:

     To ensure that only one instance of a class, and provide global access point;

Features:

 1. constructor privatization, it is not a direct definition object class: private: Csingle () {};

 2. Define a type as a static member of the class itself pointers: static CSingleton * m_singleInstance;

 3. Define a static member function returns a pointer to the class itself as a type of:

      static CSingleton* getSingleInstance(){

                if(m_singleInstance == nullptr)  m_singleInstance = new CSingleton;

                return m_singleInstance;

     }

  4. External () function to obtain a unique instance of this directly CSingleton :: getSingleInstance;

 

Singleton and multithreading

Preventing competition:

1. multithreaded access, need synchronization mechanisms: Add mutex kernel object like after entering getSingleInstance function for synchronization;

class CSingleton
{
public:
	~CSingleton() {};
	static CSingleton* m_sticSingleInstance;
	static CSingleton* GetSingleInstance();
private:
	CSingleton()  {};
};

#include "CSingleton.h"
#include <boost/thread/mutex.hpp>
#include <boost/thread/lock_guard.hpp>
boost::mutex g_mutex;
CSingleton* CSingleton::m_sticSingleInstance = nullptr;

CSingleton* CSingleton::GetSingleInstance()
{
	boost::lock_guard<boost::mutex> lock(g_mutex);//同步锁
	if (m_sticSingleInstance == nullptr) {
		m_sticSingleInstance = new CSingleton;	
	}	
	return m_sticSingleInstance;
}

2. The advance distribution of good m_singleInstance instance, will achieve new CSingleton when static member initialization m_singleInstance instance, instead of getSingleInstance () function and then create an instance of an object;


#include "CSingleton.h"

//初始化就创建实例,不会创建有多个实例
CSingleton* CSingleton::m_sticSingleInstance = new CSingleton;

CSingleton* CSingleton::GetSingleInstance()
{
	return m_sticSingleInstance;
}

3. double-checked locking, using the "double check lock", volatile modified static member m_singleInstance, in getSingleInstance function, first check whether the instance has been created, if not already created, only to be synchronized; this way, there will only sync for the first time operation, there will be no subsequent synchronization operation using getSingleInstance function, reducing consumption;


#include "CSingleton.h"
#include <boost/thread/mutex.hpp>
#include <boost/thread/lock_guard.hpp>
boost::mutex g_mutex;
CSingleton* CSingleton::m_sticSingleInstance = nullptr;

CSingleton* CSingleton::GetSingleInstance()
{
	if (m_sticSingleInstance == nullptr) {
//判断是否为nullptr后再加锁
		boost::unique_lock<boost::mutex> lock(g_mutex);
		if (m_sticSingleInstance == nullptr) {
			m_sticSingleInstance = new CSingleton;
		}
		lock.unlock();
	}
	return m_sticSingleInstance;
}
发布了69 篇原创文章 · 获赞 10 · 访问量 3万+

Guess you like

Origin blog.csdn.net/u010096608/article/details/103888550