OSRefTable 用法

typedef OSHashTable<OSRef, OSRefKey> OSRefHashTable;
typedef OSHashTableIter<OSRef, OSRefKey> OSRefHashTableIter;
class OSRefTable
{
public:

	enum
	{
		kDefaultTableSize = 1193 //UInt32
	};

	//创建hash表的大小RefTable因为采用链表连接,所以能够存储的元素是无限的,此处的大小仅仅是链表内数组的大小
	OSRefTable(UInt32 tableSize = kDefaultTableSize) : fTable(tableSize), fMutex() {}
	~OSRefTable() {}

	//Allows access to the mutex in case you need to lock the table down
	//between operations
	OSMutex*    GetMutex()      { return &fMutex; }
	OSRefHashTable* GetHashTable() { return &fTable; }
	//向RefTable表中注册一个ref,确保该ref的key之前没有,否则会注册失败
	OS_Error        Register(OSRef* ref);

	//注册或者引用计数加1:如果table中没有找到该元素,则注册,否则引用计数加1
	OSRef*              RegisterOrResolve(OSRef* inRef);
	//注销一个ref,当引用计数<= refCount时注销,从table表中删除。如果引用计数>refCount,则线程阻塞,
	//直到其他线程不在使用该ref(调用release)时,才注销ref。该函数会阻塞。
	void        UnRegister(OSRef* ref, UInt32 refCount = 0);
	//该函数与UnRegister类似,但不会阻塞。当发现有其他线程引用该ref时,则函数直接返回。
	//否则注销该ref。
	Bool16      TryUnRegister(OSRef* ref, UInt32 refCount = 0);
	//引用计数refCount加1,用完之后需要调用Release
	OSRef*      Resolve(StrPtrLen*  inString);
	//引用计数refCount减1
	void        Release(OSRef*  inRef);
	//修改table中的ref,首先查找要修改的key是否存在,如果不存在什么也不做。否则删除该ref,然后增加newref。
	//注意,在调用完该函数后,一定要将oldref注销UnRegister
	void        Swap(OSRef* newRef);
	UInt32      GetNumRefsInTable() { UInt64 result =  fTable.GetNumEntries(); Assert(result < kUInt32_Max); return (UInt32) result; }

private:


	//all this object needs to do its job is an atomic hashtable
	OSRefHashTable  fTable;
	OSMutex         fMutex;
};


class OSRefReleaser
{
public:

	OSRefReleaser(OSRefTable* inTable, OSRef* inRef) : fOSRefTable(inTable), fOSRef(inRef) {}
	~OSRefReleaser() { fOSRefTable->Release(fOSRef); }

	OSRef*          GetRef() { return fOSRef; }

private:

	OSRefTable*     fOSRefTable;
	OSRef*          fOSRef;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunxiaopengsun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值