码迷,mamicode.com
首页 > 编程语言 > 详细

非线程安全对象?

时间:2014-08-08 11:58:15      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:blog   for   2014   art   ar   div   new   log   

今天的微博有人讨论到对象池,我想到之前项目的实现,应该用模板来实现啊,唉,还是被前人的想法给框定了,只是实现一个特别简单,花了几分钟写了个:

const int DefaultPoolSize = 1024;
template <class T>
class CSSObejctPool{
private:
	queue<T*> m_OriBlock;
	queue<T*> m_ObjectBlock;
	const INT32 m_DefaultBlockSize; 
public:
	~CSSObejctPool(){
		while (!m_OriBlock.empty()){
			T* pBlock = m_OriBlock.front();
			delete []pBlock;
			m_OriBlock.pop();
		}
	}

	CSSObejctPool(INT32 blockSize = DefaultPoolSize):m_DefaultBlockSize(blockSize){
	}

	T* GetObject(){
		if (true == m_ObjectBlock.empty()){
			T* pNewObject = new T[m_DefaultBlockSize];
			m_OriBlock.push(pNewObject);
			for (int i = 0; i < m_DefaultBlockSize; ++i){
				m_ObjectBlock.push(pNewObject+i);
			}
		}

		T* pGetObject = m_ObjectBlock.front();
		m_ObjectBlock.pop();
		return pGetObject;
	}

	void ReleaseObejct(T* pObject){
		if (0 == pObject){
			return;
		}

		m_ObjectBlock.push(pObject);
	}

	void Clear(){
		while (!m_ObjectBlock.empty()){
			T* pObject = m_ObjectBlock.front();
			pObject->Clear();
			m_ObjectBlock.pop();
		}

		queue<T*> tempBlock;
		while (!m_OriBlock.empty()){
			T* pBlock = m_OriBlock.front();
			for (INT32 i = 0; i < m_DefaultBlockSize; ++i){
				m_ObjectBlock.push(pBlock + i);
			}
			
			tempBlock.push(pBlock);
			m_OriBlock.pop();
		}

		m_ObjectBlock = tempBlock;
	}
};


等下再实现个线程安全的。

非线程安全对象?,布布扣,bubuko.com

非线程安全对象?

标签:blog   for   2014   art   ar   div   new   log   

原文地址:http://www.cnblogs.com/yxwkf/p/3898629.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!