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;
};
OSRefTable 用法
最新推荐文章于 2021-08-16 15:53:32 发布