缓存管理器实现


1.实现代码

代码如下:

#ifndef H_CACHEMGR
#define H_CACHEMGR

#include <ace/Hash_Map_Manager.h>
#include <algorithm>
#include <vector>
using namespace std;

template <class T> class CCachedItem {
public:
	T obj_;
	unsigned int use_count_; ///< 使用计数
public:
	CCachedItem():obj_(0),use_count_(0) {
	}
};


template <class T> int remove_out_cmp(pair<CCachedItem<T>*,int> p1,pair<CCachedItem<T>*,int>  p2) {
	return p1.second < p2.second;
}

template <class Key,class T> class CCacheMgr {
public:
	unsigned int max_size_;
    ACE_Hash_Map_Manager<Key,CCachedItem<T>*,ACE_Thread_Mutex> m_;
public:
	CCacheMgr():max_size_(2048) {
	}
	int Get(Key key,T &o) {
		CCachedItem<T>* wo = 0;
		m_.find(key,wo);
		if (wo) {
			o = wo->obj_;
			wo->use_count_++;
			return 0;
		}
		return -1;
	}
	int Remove(Key key) {
		CCachedItem<T>* wo=0;
		m_.unbind(key,wo);
		if (wo) {
			wo->obj_->Release();
			delete wo;
			return 0;
		}
		return -1;
	}

	int RemoveOut(int n) {
		ACE_Hash_Map_Manager<Key,CCachedItem<T>*,ACE_Thread_Mutex>::ENTRY *entry = 0;
		ACE_Hash_Map_Manager<Key,CCachedItem<T>*,ACE_Thread_Mutex>::ITERATOR iter(m_);
		vector<pair<CCachedItem<T>*,int> > v;
		while(iter.next(entry)) {
			CCachedItem<T>* o = entry->int_id_;
			v.push_back(make_pair(o,o->use_count_));
			iter.advance();
		}
		sort(v.begin(),v.end(),remove_out_cmp<T>);
		for (int i=0;i<n;i++) {
			CCachedItem<T> *wo = v[i].first;
			Remove(wo->obj_->GetKeyValue());
		}
		return 0;
	}
	int Add(Key key,T o) {
		if (m_.current_size()>max_size_) {
			RemoveOut((max_size_+4)/5);
		}
		CCachedItem<T>* wo = new CCachedItem<T>;
		wo->obj_ = o;
		CCachedItem<T>* old_wo = 0;
		m_.rebind(key,wo,old_wo);
		if (old_wo) {
			old_wo->obj_->Release();
			delete old_wo;
		}
		return 0;
	}

};
#endif


2.测试代码

#include "CacheMgr.h"
struct stData {
	int n_;

	stData(int n):n_(n) {
	}
	void Release() {
		delete this;
	}
	int GetKeyValue() {
		return n_;
	}
};


int test() {
	CCacheMgr<int,stData*> mgr;
	mgr.max_size_ = 2;
	mgr.Add(1,new stData(1));
	mgr.Add(2,new stData(2));

	stData *obj;
	mgr.Get(1,obj);
	mgr.Get(1,obj);
	mgr.Get(2,obj);

	mgr.Add(3,new stData(3));
	mgr.Add(4,new stData(4));

	obj = 0;
	mgr.Get(3,obj);
	
	return 0;
}	

3.应用

    class CMyGoodsMgr : public IMyGoodsMgr,public CRootObject {
        CCacheMgr<ACE_CString,CMyGoods*> m_mapMyGoods;
    };






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值