live555 源码分析:基础设施
live555 由多個模塊組成,其中 UsageEnvironment 、 BasicUsageEnvironment 和 groupsock 分別提供了事件循環,輸入輸出,基本的數據結構,以及網絡 IO 等功能,它們可以看作 live555 的基礎設施。對于 live555 的源碼分析,就從這些基礎設施,基本的數據結構開始。
HashTable
首先來看 HashTable,這是 live555 定義的一個范型關聯容器。
UsageEnvironment 的 HashTable
UsageEnvironment 中的 HashTable 類定義了接口,該接口定義如下:
class HashTable { public:virtual ~HashTable();// The following must be implemented by a particular// implementation (subclass):static HashTable* create(int keyType);virtual void* Add(char const* key, void* value) = 0;// Returns the old value if different, otherwise 0virtual Boolean Remove(char const* key) = 0;virtual void* Lookup(char const* key) const = 0;// Returns 0 if not foundvirtual unsigned numEntries() const = 0;Boolean IsEmpty() const { return numEntries() == 0; }// Used to iterate through the members of the table:class Iterator {public:// The following must be implemented by a particular// implementation (subclass):static Iterator* create(HashTable const& hashTable);virtual ~Iterator();virtual void* next(char const*& key) = 0; // returns 0 if noneprotected:Iterator(); // abstract base class};// A shortcut that can be used to successively remove each of// the entries in the table (e.g., so that their values can be// deleted, if they happen to be pointers to allocated memory).void* RemoveNext();// Returns the first entry in the table.// (This is useful for deleting each entry in the table, if the entry's destructor also removes itself from the table.)void* getFirst(); protected:HashTable(); // abstract base class };// Warning: The following are deliberately the same as in // Tcl's hash table implementation int const STRING_HASH_KEYS = 0; int const ONE_WORD_HASH_KEYS = 1;盡管 HashTable 要定義為范型關聯容器,然而它沒有使用 C++ 的模板。HashTable 要求鍵為一個 C 風格的字符串,即 char const*,而值為一個 void*,以此可以表示各種不同類型的值。就像 C++ 標準庫中的許多容器一眼,HashTable 內部還定義了一個迭代器類,用來遍歷這個容器。
其它添加、移除、查找元素等操作,與其它的普通容器設計并沒有太大的不同。
HashTable 類實現了公共的與具體存儲結構無關的兩個模板函數 RemoveNext() 和 getFirst(),這兩個函數分別用于移除容器中的下一個元素并返回元素的值,及得到容器中的第一個元素,它們的實現如下:
#include "HashTable.hh"HashTable::HashTable() { }HashTable::~HashTable() { }HashTable::Iterator::Iterator() { }HashTable::Iterator::~Iterator() {}void* HashTable::RemoveNext() {Iterator* iter = Iterator::create(*this);char const* key;void* removedValue = iter->next(key);if (removedValue != 0) Remove(key);delete iter;return removedValue; }void* HashTable::getFirst() {Iterator* iter = Iterator::create(*this);char const* key;void* firstValue = iter->next(key);delete iter;return firstValue; }這兩個函數,都借助于容器的迭代器來實現。Iterator 類的 next(char const*& key) 接收一個傳出參數,用于將鍵返回給調用者。
從接口定義的角度來看 live555 定義的 HashTable。它的 Iterator 類對象是由 Iterator 類的靜態方法 create(HashTable const& hashTable) 創建的,但銷毀創建的對象的職責卻是在調用者這里,這大大破壞了 HashTable 接口的實現的靈活性,比如創建的對象因此而無法做緩存。
HashTable 類及其迭代器類 Iterator 各自定義了一個靜態方法 create()。這里使用了橋接的方式,HashTable 的這個方法像一座橋一樣,把 HashTable 接口與接口的實現聯系了起來。這個類靜態函數都在實現接口的類中定義。
HashTable 有兩種類型,分別用兩個整型值來標識,STRING_HASH_KEYS 和 ONE_WORD_HASH_KEYS。當然,依賴于在 create() 方法中是根據 HashTable 類型創建相同類的對象還是創建不同類的對象,可以將 create() 方法的設計理解為是橋接,或者工廠方法。
BasicUsageEnvironment 的 BasicHashTable
BasicUsageEnvironment 中的 BasicHashTable 提供了一個 HashTable 的實現。BasicHashTable 的定義如下:
// A simple hash table implementation, inspired by the hash table // implementation used in Tcl 7.6: <http://www.tcl.tk/>#define SMALL_HASH_TABLE_SIZE 4class BasicHashTable: public HashTable { private:class TableEntry; // forwardpublic:BasicHashTable(int keyType);virtual ~BasicHashTable();// Used to iterate through the members of the table:class Iterator; friend class Iterator; // to make Sun's C++ compiler happyclass Iterator: public HashTable::Iterator {public:Iterator(BasicHashTable const& table);private: // implementation of inherited pure virtual functionsvoid* next(char const*& key); // returns 0 if noneprivate:BasicHashTable const& fTable;unsigned fNextIndex; // index of next bucket to be enumerated after thisTableEntry* fNextEntry; // next entry in the current bucket};private: // implementation of inherited pure virtual functionsvirtual void* Add(char const* key, void* value);// Returns the old value if different, otherwise 0virtual Boolean Remove(char const* key);virtual void* Lookup(char const* key) const;// Returns 0 if not foundvirtual unsigned numEntries() const;private:class TableEntry {public:TableEntry* fNext;char const* key;void* value;};TableEntry* lookupKey(char const* key, unsigned& index) const;// returns entry matching "key", or NULL if noneBoolean keyMatches(char const* key1, char const* key2) const;// used to implement "lookupKey()"TableEntry* insertNewEntry(unsigned index, char const* key);// creates a new entry, and inserts it in the tablevoid assignKey(TableEntry* entry, char const* key);// used to implement "insertNewEntry()"void deleteEntry(unsigned index, TableEntry* entry);void deleteKey(TableEntry* entry);// used to implement "deleteEntry()"void rebuild(); // rebuilds the table as its size increasesunsigned hashIndexFromKey(char const* key) const;// used to implement many of the routines aboveunsigned randomIndex(uintptr_t i) const {return (unsigned)(((i*1103515245) >> fDownShift) & fMask);}private:TableEntry** fBuckets; // pointer to bucket arrayTableEntry* fStaticBuckets[SMALL_HASH_TABLE_SIZE];// used for small tablesunsigned fNumBuckets, fNumEntries, fRebuildSize, fDownShift, fMask;int fKeyType; };BasicHashTable 定義了一個類 TableEntry,用于表示鍵-值對。fNext 字段用于指向計算的鍵的哈希值沖突的不同的鍵-值對中的下一個。
來看 BasicHashTable 的創建:
BasicHashTable::BasicHashTable(int keyType): fBuckets(fStaticBuckets), fNumBuckets(SMALL_HASH_TABLE_SIZE),fNumEntries(0), fRebuildSize(SMALL_HASH_TABLE_SIZE*REBUILD_MULTIPLIER),fDownShift(28), fMask(0x3), fKeyType(keyType) {for (unsigned i = 0; i < SMALL_HASH_TABLE_SIZE; ++i) {fStaticBuckets[i] = NULL;} } . . . . . . HashTable* HashTable::create(int keyType) {return new BasicHashTable(keyType); }BasicHashTable 用 TableEntry 指針的數組保存所有的鍵-值對。在該類對象創建時,一個小的 TableEntry 指針數組 fStaticBuckets 會隨著對象的創建而創建,在 BasicHashTable 中元素比較少時,直接在這個數組中保存鍵值對,以此來優化當元素比較少的性能,降低內存分配的開銷。
fBuckets 指向保存鍵-值對的 TableEntry 指針數組,在對象創建初期,它指向 fStaticBuckets,而在哈希桶擴容時,它指向新分配的 TableEntry 指針數組。對于容器中元素的訪問,都通過
fBuckets 來完成。fNumBuckets 用于保存 TableEntry 指針數組的長度。fNumEntries 用于保存容器中鍵-值對的個數。fRebuildSize 為哈希桶擴容的閾值,即當 BasicHashTable 中保存的鍵值對超過該值時,哈希桶需要擴容。fDownShift 和 fMask 用于計算哈希值,并把哈希值映射到哈希桶容量范圍內。
向 BasicHashTable 中插入元素
可以通過 Add(char const* key, void* value) 向 BasicHashTable 中插入元素,這個函數的定義如下:
void* BasicHashTable::Add(char const* key, void* value) {void* oldValue;unsigned index;TableEntry* entry = lookupKey(key, index);if (entry != NULL) {// There's already an item with this keyoldValue = entry->value;} else {// There's no existing entry; create a new one:entry = insertNewEntry(index, key);oldValue = NULL;}entry->value = value;// If the table has become too large, rebuild it with more buckets:if (fNumEntries >= fRebuildSize) rebuild();return oldValue; }向 BasicHashTable 中插入元素的過車大致如下:
1. 查找 BasicHashTable 中與要插入的鍵-值對的鍵匹配的元素 TableEntry。
2. 若找到,把該元素的舊的值保存在 oldValue 中。
3. 若沒有找到,則通過 insertNewEntry(index, key) 創建一個 TableEntry 并加入到哈希桶中,oldValue 被賦值為 NULL。
4. 把要插入的鍵-值對的值保存進新創建或找到的 TableEntry 中。
5. 如果 BasicHashTable 中的元素個數超出 fRebuildSize 的大小,則對哈希桶擴容。
6. 返回元素的舊的值。
查找 BasicHashTable 中與要插入的鍵-值對的鍵匹配的元素 TableEntry 的過程如下:
BasicHashTable::TableEntry* BasicHashTable ::lookupKey(char const* key, unsigned& index) const {TableEntry* entry;index = hashIndexFromKey(key);for (entry = fBuckets[index]; entry != NULL; entry = entry->fNext) {if (keyMatches(key, entry->key)) break;}return entry; }Boolean BasicHashTable ::keyMatches(char const* key1, char const* key2) const {// The way we check the keys for a match depends upon their type:if (fKeyType == STRING_HASH_KEYS) {return (strcmp(key1, key2) == 0);} else if (fKeyType == ONE_WORD_HASH_KEYS) {return (key1 == key2);} else {unsigned* k1 = (unsigned*)key1;unsigned* k2 = (unsigned*)key2;for (int i = 0; i < fKeyType; ++i) {if (k1[i] != k2[i]) return False; // keys differ}return True;} } . . . . . . unsigned BasicHashTable::hashIndexFromKey(char const* key) const {unsigned result = 0;if (fKeyType == STRING_HASH_KEYS) {while (1) {char c = *key++;if (c == 0) break;result += (result<<3) + (unsigned)c;}result &= fMask;} else if (fKeyType == ONE_WORD_HASH_KEYS) {result = randomIndex((uintptr_t)key);} else {unsigned* k = (unsigned*)key;uintptr_t sum = 0;for (int i = 0; i < fKeyType; ++i) {sum += k[i];}result = randomIndex(sum);}return result; }lookupKey() 首先通過 hashIndexFromKey(key) 根據鍵值對的鍵計算哈希值,并把該值映射到哈希桶容量范圍內,得到索引。然后根據得到的索引,查找與傳入的鍵匹配的元素。
這里可以更加清晰地看到,不同類型的 HashTable 之間的區別主要在于對待鍵的方式不同。STRING_HASH_KEYS 型的 HashTable,其鍵為傳入的字符串指針指向的字符串的內容,而
ONE_WORD_HASH_KEYS 型的 HashTable,其鍵則為傳入的字符串指針本身。
計算最終的哈希值,并把該值映射到哈希桶容量范圍內,得到索引的過程如下:
unsigned randomIndex(uintptr_t i) const {return (unsigned)(((i*1103515245) >> fDownShift) & fMask);}insertNewEntry(index, key) 創建一個 TableEntry 并加入到哈希桶中的過程如下:
BasicHashTable::TableEntry* BasicHashTable ::insertNewEntry(unsigned index, char const* key) {TableEntry* entry = new TableEntry();entry->fNext = fBuckets[index];fBuckets[index] = entry;++fNumEntries;assignKey(entry, key);return entry; }void BasicHashTable::assignKey(TableEntry* entry, char const* key) {// The way we assign the key depends upon its type:if (fKeyType == STRING_HASH_KEYS) {entry->key = strDup(key);} else if (fKeyType == ONE_WORD_HASH_KEYS) {entry->key = key;} else if (fKeyType > 0) {unsigned* keyFrom = (unsigned*)key;unsigned* keyTo = new unsigned[fKeyType];for (int i = 0; i < fKeyType; ++i) keyTo[i] = keyFrom[i];entry->key = (char const*)keyTo;} }可見插入的過程主要為,
1. 創建 TableEntry 對象,并把它插入到鍵所對應的 TableEntry 指針數組中的 TableEntry 元素鏈的頭部。
2. 增加容器中元素個數的計數。
3. 為 TableEntry 分配傳入的鍵。
依據 HashTable 類型的不同,分配鍵的方式也不同。
1. 對于 STRING_HASH_KEYS 型的 HashTable,需要將傳入的字符串指針指向的字符串的內容復制一份,賦值給 TableEntry 的 key。
2. 對于 ONE_WORD_HASH_KEYS 型的 HashTable,需要將傳入的字符串指針本身,賦值給 TableEntry 的 key。
3. 對于 fKeyType 大于 0 的情況,需要將傳入的字符串指針指向的字符串的內容的前 (sizeof(unsigned) * fKeyType) 個字節復制一份,賦值給 TableEntry 的 key。這種代碼真是看得人膽顫心驚,萬一傳入的 key 字符串長度小于 (sizeof(unsigned) * fKeyType) 個字節呢?。。。
對比 keyMatches() 和 assignKey() 函數的實現,不難發現,當 HashTable 類型 fKeyType 大于0,且不是 ONE_WORD_HASH_KEYS 時,要求作為哈希表中鍵值對的鍵的字符串的長度固定為 (sizeof(unsigned) * fKeyType) 個字節。
然后來看,BasicHashTable 中對哈希桶擴容的過程:
void BasicHashTable::rebuild() {// Remember the existing table size:unsigned oldSize = fNumBuckets;TableEntry** oldBuckets = fBuckets;// Create the new sized table:fNumBuckets *= 4;fBuckets = new TableEntry*[fNumBuckets];for (unsigned i = 0; i < fNumBuckets; ++i) {fBuckets[i] = NULL;}fRebuildSize *= 4;fDownShift -= 2;fMask = (fMask<<2)|0x3;// Rehash the existing entries into the new table:for (TableEntry** oldChainPtr = oldBuckets; oldSize > 0;--oldSize, ++oldChainPtr) {for (TableEntry* hPtr = *oldChainPtr; hPtr != NULL;hPtr = *oldChainPtr) {*oldChainPtr = hPtr->fNext;unsigned index = hashIndexFromKey(hPtr->key);hPtr->fNext = fBuckets[index];fBuckets[index] = hPtr;}}// Free the old bucket array, if it was dynamically allocated:if (oldBuckets != fStaticBuckets) delete[] oldBuckets; }在這里就是,
1. 為 fBuckets 分配一塊新的內存,容量為原來的4倍。
2. 適當更新 fNumBuckets,fRebuildSize,fDownShift 和 fMask 等。
3. 將老的 fBuckets 中的元素,依據元素的 key 和新的哈希桶的容量,搬到新的 fBuckets 中。
4. 根據需要釋放老的 fBuckets 的內存。
在 BasicHashTable 中查找元素
然后來看在 BasicHashTable 中查找元素的過程:
void* BasicHashTable::Lookup(char const* key) const {unsigned index;TableEntry* entry = lookupKey(key, index);if (entry == NULL) return NULL; // no such entryreturn entry->value; }這個過程主要是根據 key,通過 lookupKey() 查找到對應的元素 TableEntry,然后返回其 value。
移除 BasicHashTable 中的元素
來看移除 BasicHashTable 中的元素的過程:
Boolean BasicHashTable::Remove(char const* key) {unsigned index;TableEntry* entry = lookupKey(key, index);if (entry == NULL) return False; // no such entrydeleteEntry(index, entry);return True; } . . . . . . void BasicHashTable::deleteEntry(unsigned index, TableEntry* entry) {TableEntry** ep = &fBuckets[index];Boolean foundIt = False;while (*ep != NULL) {if (*ep == entry) {foundIt = True;*ep = entry->fNext;break;}ep = &((*ep)->fNext);}if (!foundIt) { // shouldn't happen #ifdef DEBUGfprintf(stderr, "BasicHashTable[%p]::deleteEntry(%d,%p): internal error - not found (first entry %p", this, index, entry, fBuckets[index]);if (fBuckets[index] != NULL) fprintf(stderr, ", next entry %p", fBuckets[index]->fNext);fprintf(stderr, ")\n"); #endif}--fNumEntries;deleteKey(entry);delete entry; }void BasicHashTable::deleteKey(TableEntry* entry) {// The way we delete the key depends upon its type:if (fKeyType == ONE_WORD_HASH_KEYS) {entry->key = NULL;} else {delete[] (char*)entry->key;entry->key = NULL;} }移除 BasicHashTable 中的元素的過程,也是免不了要先找到元素在 BasicHashTable 中的 TableEntry 的,找到之后,通過 deleteEntry() 移除元素。
在 deleteEntry() 中,先把元素從 BasicHashTable 中移除出去,然后通過 deleteKey() 釋放 key 占用的內存,隨后釋放 TableEntry 本身占用的內存。這里把 TableEntry 從 BasicHashTable 中移除出去采用了下面這種方法:
TableEntry** ep = &fBuckets[index];Boolean foundIt = False;while (*ep != NULL) {if (*ep == entry) {foundIt = True;*ep = entry->fNext;break;}ep = &((*ep)->fNext);}通過二級指針,遍歷鏈表一趟,就將元素移除出去了。記得這是這中場景下 Linus 大神鼓勵的一種寫法。從鏈表中刪除一個元素,用好幾個臨時變量,或者加許多判斷的方法,都弱爆了。
通過 Iterator 遍歷 BasicHashTable
可以使用 BasicHashTable 中定義的 Iterator 來遍歷它。過程如下:
BasicHashTable::Iterator::Iterator(BasicHashTable const& table): fTable(table), fNextIndex(0), fNextEntry(NULL) { }void* BasicHashTable::Iterator::next(char const*& key) {while (fNextEntry == NULL) {if (fNextIndex >= fTable.fNumBuckets) return NULL;fNextEntry = fTable.fBuckets[fNextIndex++];}BasicHashTable::TableEntry* entry = fNextEntry;fNextEntry = entry->fNext;key = entry->key;return entry->value; } . . . . . . HashTable::Iterator* HashTable::Iterator::create(HashTable const& hashTable) {// "hashTable" is assumed to be a BasicHashTablereturn new BasicHashTable::Iterator((BasicHashTable const&)hashTable); }BasicHashTable 的 fBuckets 中的每個元素都保存一個 TableEntry 的鏈表。在這里會逐個鏈表地遍歷。
live555 定義的 HashTable 的內容就是這些了。
UsageEnvironment
live555 中,UsageEnvironment 類扮演一個簡單的控制器的角色。UsageEnvironment 模塊中,UsageEnvironment 類的定義如下:
class TaskScheduler; // forward// An abstract base class, subclassed for each use of the libraryclass UsageEnvironment { public:Boolean reclaim();// returns True iff we were actually able to delete our object// task scheduler:TaskScheduler& taskScheduler() const {return fScheduler;}// result message handling:typedef char const* MsgString;virtual MsgString getResultMsg() const = 0;virtual void setResultMsg(MsgString msg) = 0;virtual void setResultMsg(MsgString msg1, MsgString msg2) = 0;virtual void setResultMsg(MsgString msg1, MsgString msg2, MsgString msg3) = 0;virtual void setResultErrMsg(MsgString msg, int err = 0) = 0;// like setResultMsg(), except that an 'errno' message is appended. (If "err == 0", the "getErrno()" code is used instead.)virtual void appendToResultMsg(MsgString msg) = 0;virtual void reportBackgroundError() = 0;// used to report a (previously set) error message within// a background eventvirtual void internalError(); // used to 'handle' a 'should not occur'-type error condition within the library.// 'errno'virtual int getErrno() const = 0;// 'console' output:virtual UsageEnvironment& operator<<(char const* str) = 0;virtual UsageEnvironment& operator<<(int i) = 0;virtual UsageEnvironment& operator<<(unsigned u) = 0;virtual UsageEnvironment& operator<<(double d) = 0;virtual UsageEnvironment& operator<<(void* p) = 0;// a pointer to additional, optional, client-specific statevoid* liveMediaPriv;void* groupsockPriv;protected:UsageEnvironment(TaskScheduler& scheduler); // abstract base classvirtual ~UsageEnvironment(); // we are deleted only by reclaim()private:TaskScheduler& fScheduler; };UsageEnvironment 類持有 TaskScheduler 的引用,并提供文本的輸出操作,用于輸出信息,其它還提供了獲取 errno 的操作,在發生內部錯誤時的處理程序 internalError(),以及銷毀自身的操作。UsageEnvironment 類本身實現了如下這幾個函數:
Boolean UsageEnvironment::reclaim() { // We delete ourselves only if we have no remainining state:if (liveMediaPriv == NULL && groupsockPriv == NULL) {delete this;return True;}return False; }UsageEnvironment::UsageEnvironment(TaskScheduler& scheduler) : liveMediaPriv(NULL), groupsockPriv(NULL), fScheduler(scheduler) { }UsageEnvironment::~UsageEnvironment() { }// By default, we handle 'should not occur'-type library errors by calling abort(). Subclasses can redefine this, if desired. // (If your runtime library doesn't define the "abort()" function, then define your own (e.g., that does nothing).) void UsageEnvironment::internalError() {abort(); }這些函數都比較簡單,這里不再贅述。
UsageEnvironment 是一個接口類,BasicUsageEnvironment 模塊中,通過兩個類 BasicUsageEnvironment 和 BasicUsageEnvironment0,提供了它的一個實現。BasicUsageEnvironment0 類提供了那組直接操作字符串的函數的實現,該類的定義如下:
class BasicUsageEnvironment0: public UsageEnvironment { public:// redefined virtual functions:virtual MsgString getResultMsg() const;virtual void setResultMsg(MsgString msg);virtual void setResultMsg(MsgString msg1,MsgString msg2);virtual void setResultMsg(MsgString msg1,MsgString msg2,MsgString msg3);virtual void setResultErrMsg(MsgString msg, int err = 0);virtual void appendToResultMsg(MsgString msg);virtual void reportBackgroundError();protected:BasicUsageEnvironment0(TaskScheduler& taskScheduler);virtual ~BasicUsageEnvironment0();private:void reset();char fResultMsgBuffer[RESULT_MSG_BUFFER_MAX];unsigned fCurBufferSize;unsigned fBufferMaxSize; };這個類定義了一個緩沖區,大小為 RESULT_MSG_BUFFER_MAX。類的實現如下:
BasicUsageEnvironment0::BasicUsageEnvironment0(TaskScheduler& taskScheduler): UsageEnvironment(taskScheduler),fBufferMaxSize(RESULT_MSG_BUFFER_MAX) {reset(); }BasicUsageEnvironment0::~BasicUsageEnvironment0() { }void BasicUsageEnvironment0::reset() {fCurBufferSize = 0;fResultMsgBuffer[fCurBufferSize] = '\0'; }// Implementation of virtual functions:char const* BasicUsageEnvironment0::getResultMsg() const {return fResultMsgBuffer; }void BasicUsageEnvironment0::setResultMsg(MsgString msg) {reset();appendToResultMsg(msg); }void BasicUsageEnvironment0::setResultMsg(MsgString msg1, MsgString msg2) {setResultMsg(msg1);appendToResultMsg(msg2); }void BasicUsageEnvironment0::setResultMsg(MsgString msg1, MsgString msg2,MsgString msg3) {setResultMsg(msg1, msg2);appendToResultMsg(msg3); }void BasicUsageEnvironment0::setResultErrMsg(MsgString msg, int err) {setResultMsg(msg);if (err == 0) err = getErrno(); . . . . . .appendToResultMsg(strerror(err)); #endif }void BasicUsageEnvironment0::appendToResultMsg(MsgString msg) {char* curPtr = &fResultMsgBuffer[fCurBufferSize];unsigned spaceAvailable = fBufferMaxSize - fCurBufferSize;unsigned msgLength = strlen(msg);// Copy only enough of "msg" as will fit:if (msgLength > spaceAvailable-1) {msgLength = spaceAvailable-1;}memmove(curPtr, (char*)msg, msgLength);fCurBufferSize += msgLength;fResultMsgBuffer[fCurBufferSize] = '\0'; }void BasicUsageEnvironment0::reportBackgroundError() {fputs(getResultMsg(), stderr); }這組函數提供了把傳入的字符串,加進緩沖區,以及把緩沖區中的內容輸出到標準輸出的功能。
BasicUsageEnvironment 類則提供了那組用于輸出基本數據類型的操作符。這個類的定義如下:
class BasicUsageEnvironment: public BasicUsageEnvironment0 { public:static BasicUsageEnvironment* createNew(TaskScheduler& taskScheduler);// redefined virtual functions:virtual int getErrno() const;virtual UsageEnvironment& operator<<(char const* str);virtual UsageEnvironment& operator<<(int i);virtual UsageEnvironment& operator<<(unsigned u);virtual UsageEnvironment& operator<<(double d);virtual UsageEnvironment& operator<<(void* p);protected:BasicUsageEnvironment(TaskScheduler& taskScheduler);// called only by "createNew()" (or subclass constructors)virtual ~BasicUsageEnvironment(); };定義比較簡單。然后來看它的實現:
BasicUsageEnvironment::BasicUsageEnvironment(TaskScheduler& taskScheduler) : BasicUsageEnvironment0(taskScheduler) { . . . . . . }BasicUsageEnvironment::~BasicUsageEnvironment() { }BasicUsageEnvironment* BasicUsageEnvironment::createNew(TaskScheduler& taskScheduler) {return new BasicUsageEnvironment(taskScheduler); }int BasicUsageEnvironment::getErrno() const { #if defined(__WIN32__) || defined(_WIN32) || defined(_WIN32_WCE)return WSAGetLastError(); #elsereturn errno; #endif }UsageEnvironment& BasicUsageEnvironment::operator<<(char const* str) {if (str == NULL) str = "(NULL)"; // sanity checkfprintf(stderr, "%s", str);return *this; }UsageEnvironment& BasicUsageEnvironment::operator<<(int i) {fprintf(stderr, "%d", i);return *this; }UsageEnvironment& BasicUsageEnvironment::operator<<(unsigned u) {fprintf(stderr, "%u", u);return *this; }UsageEnvironment& BasicUsageEnvironment::operator<<(double d) {fprintf(stderr, "%f", d);return *this; }UsageEnvironment& BasicUsageEnvironment::operator<<(void* p) {fprintf(stderr, "%p", p);return *this; }BasicUsageEnvironment 類還提供了一個靜態的創建對象的函數 createNew() 用來創建 BasicUsageEnvironment 的對象。對于那些輸出操作符的實現,都比較直接。
感覺 live555 這組 I/O 函數的實現并不是太好,C++ 標準庫對這些接口都有著良好的實現,但 live555 似乎并沒有要引入 C++ 標準庫的打算。
TaskScheduler
TaskScheduler 是 live555 中的任務調度器,它實現了 live555 的事件循環。UsageEnvironment 模塊中,TaskScheduler 類的定義如下:
typedef void TaskFunc(void* clientData); typedef void* TaskToken; typedef u_int32_t EventTriggerId;class TaskScheduler { public:virtual ~TaskScheduler();virtual TaskToken scheduleDelayedTask(int64_t microseconds, TaskFunc* proc,void* clientData) = 0;// Schedules a task to occur (after a delay) when we next// reach a scheduling point.// (Does not delay if "microseconds" <= 0)// Returns a token that can be used in a subsequent call to// unscheduleDelayedTask() or rescheduleDelayedTask()// (but only if the task has not yet occurred).virtual void unscheduleDelayedTask(TaskToken& prevTask) = 0;// (Has no effect if "prevTask" == NULL)// Sets "prevTask" to NULL afterwards.// Note: This MUST NOT be called if the scheduled task has already occurred.virtual void rescheduleDelayedTask(TaskToken& task,int64_t microseconds, TaskFunc* proc,void* clientData);// Combines "unscheduleDelayedTask()" with "scheduleDelayedTask()"// (setting "task" to the new task token).// Note: This MUST NOT be called if the scheduled task has already occurred.// For handling socket operations in the background (from the event loop):typedef void BackgroundHandlerProc(void* clientData, int mask);// Possible bits to set in "mask". (These are deliberately defined// the same as those in Tcl, to make a Tcl-based subclass easy.)#define SOCKET_READABLE (1<<1)#define SOCKET_WRITABLE (1<<2)#define SOCKET_EXCEPTION (1<<3)virtual void setBackgroundHandling(int socketNum, int conditionSet, BackgroundHandlerProc* handlerProc, void* clientData) = 0;void disableBackgroundHandling(int socketNum) { setBackgroundHandling(socketNum, 0, NULL, NULL); }virtual void moveSocketHandling(int oldSocketNum, int newSocketNum) = 0;// Changes any socket handling for "oldSocketNum" so that occurs with "newSocketNum" instead.virtual void doEventLoop(char volatile* watchVariable = NULL) = 0;// Causes further execution to take place within the event loop.// Delayed tasks, background I/O handling, and other events are handled, sequentially (as a single thread of control).// (If "watchVariable" is not NULL, then we return from this routine when *watchVariable != 0)virtual EventTriggerId createEventTrigger(TaskFunc* eventHandlerProc) = 0;// Creates a 'trigger' for an event, which - if it occurs - will be handled (from the event loop) using "eventHandlerProc".// (Returns 0 iff no such trigger can be created (e.g., because of implementation limits on the number of triggers).)virtual void deleteEventTrigger(EventTriggerId eventTriggerId) = 0;virtual void triggerEvent(EventTriggerId eventTriggerId, void* clientData = NULL) = 0;// Causes the (previously-registered) handler function for the specified event to be handled (from the event loop).// The handler function is called with "clientData" as parameter.// Note: This function (unlike other library functions) may be called from an external thread// - to signal an external event. (However, "triggerEvent()" should not be called with the// same 'event trigger id' from different threads.)// The following two functions are deprecated, and are provided for backwards-compatibility only:void turnOnBackgroundReadHandling(int socketNum, BackgroundHandlerProc* handlerProc, void* clientData) {setBackgroundHandling(socketNum, SOCKET_READABLE, handlerProc, clientData);}void turnOffBackgroundReadHandling(int socketNum) { disableBackgroundHandling(socketNum); }virtual void internalError(); // used to 'handle' a 'should not occur'-type error condition within the library.protected:TaskScheduler(); // abstract base class };TaskScheduler 的接口可以分為如下的幾組:
1. 調度定時器任務。這主要包括 scheduleDelayedTask()、unscheduleDelayedTask() 和 rescheduleDelayedTask() 這幾個函數,它們分別用于調度一個延遲任務,取消一個延遲任務,以及重新調度一個延遲任務。
2. 后臺調度 Socket I/O 處理操作。這主要包括 setBackgroundHandling()、disableBackgroundHandling()、moveSocketHandling()、turnOnBackgroundReadHandling() 和 turnOffBackgroundReadHandling() 這樣幾個函數,它們用于設置、修改或取消 socket 上特定 I/O 事件的處理程序。
3. 用戶事件調度。這主要包括 createEventTrigger()、deleteEventTrigger() 和 triggerEvent() 這樣幾個函數,它們用于創建、刪除及觸發一個用戶自定義事件。
4. 執行事件循環。這個由 doEventLoop() 函數完成,這個函數通常也是應用程序的主循環。
5. 內部錯誤處理程序。這個指 internalError() 函數,用于在 TaskScheduler 發生內部錯誤時,執行一些處理。
TaskScheduler 類本身提供了幾個簡單函數的實現:
TaskScheduler::TaskScheduler() { }TaskScheduler::~TaskScheduler() { }void TaskScheduler::rescheduleDelayedTask(TaskToken& task,int64_t microseconds, TaskFunc* proc,void* clientData) {unscheduleDelayedTask(task);task = scheduleDelayedTask(microseconds, proc, clientData); }// By default, we handle 'should not occur'-type library errors by calling abort(). Subclasses can redefine this, if desired. void TaskScheduler::internalError() {abort(); }它們都簡單而易于理解,這里不再贅述。
BasicUsageEnvironment 模塊中同樣提供了,TaskScheduler 接口的實現。與 UsageEnvironment 接口的情況類似,TaskScheduler 類的接口同樣由兩個類來實現,分別是 BasicTaskScheduler 和 BasicTaskScheduler0,其中
BasicTaskScheduler0 類實現我們前面提到的第 1 組,第 3 組接口,以及 doEventLoop() 的框架,而 BasicTaskScheduler 則用于實現第 2 組接口,并實現 doEventLoop() 的事件循環的循環體。
BasicTaskScheduler0 類定義如下:
class HandlerSet; // forward#define MAX_NUM_EVENT_TRIGGERS 32// An abstract base class, useful for subclassing // (e.g., to redefine the implementation of socket event handling) class BasicTaskScheduler0: public TaskScheduler { public:virtual ~BasicTaskScheduler0();virtual void SingleStep(unsigned maxDelayTime = 0) = 0;// "maxDelayTime" is in microseconds. It allows a subclass to impose a limit// on how long "select()" can delay, in case it wants to also do polling.// 0 (the default value) means: There's no maximum; just look at the delay queuepublic:// Redefined virtual functions:virtual TaskToken scheduleDelayedTask(int64_t microseconds, TaskFunc* proc,void* clientData);virtual void unscheduleDelayedTask(TaskToken& prevTask);virtual void doEventLoop(char volatile* watchVariable);virtual EventTriggerId createEventTrigger(TaskFunc* eventHandlerProc);virtual void deleteEventTrigger(EventTriggerId eventTriggerId);virtual void triggerEvent(EventTriggerId eventTriggerId, void* clientData = NULL);protected:BasicTaskScheduler0();protected:// To implement delayed operations:DelayQueue fDelayQueue;// To implement background reads:HandlerSet* fHandlers;int fLastHandledSocketNum;// To implement event triggers:EventTriggerId volatile fTriggersAwaitingHandling; // implemented as a 32-bit bitmapEventTriggerId fLastUsedTriggerMask; // implemented as a 32-bit bitmapTaskFunc* fTriggeredEventHandlers[MAX_NUM_EVENT_TRIGGERS];void* fTriggeredEventClientDatas[MAX_NUM_EVENT_TRIGGERS];unsigned fLastUsedTriggerNum; // in the range [0,MAX_NUM_EVENT_TRIGGERS) };BasicTaskScheduler0 類的成員函數,基本上就是繼承自 TaskScheduler 類中,它要實現功能的那部分接口,但它新添加了一個虛函數 SingleStep() ,用于讓其子類覆寫,實現事件循環中的單次迭代。
BasicTaskScheduler0 類的成員變量則是清晰地分為三組:fDelayQueue 用于實現定時器操作;fHandlers 和 fLastHandledSocketNum 用于實現 Socket I/O 事件處理操作;fTriggersAwaitingHandling、fLastUsedTriggerMask、fTriggeredEventHandlers、fTriggeredEventClientDatas 和 fLastUsedTriggerNum 用于實現用戶事件。
*對于 fHandlers 和 fLastHandledSocketNum,感覺實際上沒有必要在
BasicTaskScheduler0 類中定義。縱觀 BasicTaskScheduler0 類的整個實現,除初始化這兩個成員變量之外,不存在其它的訪問操作。從這兩個變量的職責來說,也不在 BasicTaskScheduler0 類的職責范圍內。感覺這兩個變量實際上放在 BasicTaskScheduler 類中更合適一點。*
BasicTaskScheduler0 類對象創建及銷毀過程如下:
BasicTaskScheduler0::BasicTaskScheduler0(): fLastHandledSocketNum(-1), fTriggersAwaitingHandling(0), fLastUsedTriggerMask(1), fLastUsedTriggerNum(MAX_NUM_EVENT_TRIGGERS-1) {fHandlers = new HandlerSet;for (unsigned i = 0; i < MAX_NUM_EVENT_TRIGGERS; ++i) {fTriggeredEventHandlers[i] = NULL;fTriggeredEventClientDatas[i] = NULL;} }BasicTaskScheduler0::~BasicTaskScheduler0() {delete fHandlers; }在類對象創建的過程中,創建和/或初始化成員對象,對象銷毀時,則銷毀成員對象。
時間的表示
在 live555 的 BasicUsageEnvironment 模塊中,用 Timeval 類來描述時間,并用 DelayInterval 來描述延遲時間。這兩個類的定義如下:
class Timeval { public:time_base_seconds seconds() const {return fTv.tv_sec;}time_base_seconds seconds() {return fTv.tv_sec;}time_base_seconds useconds() const {return fTv.tv_usec;}time_base_seconds useconds() {return fTv.tv_usec;}int operator>=(Timeval const& arg2) const;int operator<=(Timeval const& arg2) const {return arg2 >= *this;}int operator<(Timeval const& arg2) const {return !(*this >= arg2);}int operator>(Timeval const& arg2) const {return arg2 < *this;}int operator==(Timeval const& arg2) const {return *this >= arg2 && arg2 >= *this;}int operator!=(Timeval const& arg2) const {return !(*this == arg2);}void operator+=(class DelayInterval const& arg2);void operator-=(class DelayInterval const& arg2);// returns ZERO iff arg2 >= arg1protected:Timeval(time_base_seconds seconds, time_base_seconds useconds) {fTv.tv_sec = seconds; fTv.tv_usec = useconds;}private:time_base_seconds& secs() {return (time_base_seconds&)fTv.tv_sec;}time_base_seconds& usecs() {return (time_base_seconds&)fTv.tv_usec;}struct timeval fTv; }; . . . . . . class DelayInterval: public Timeval { public:DelayInterval(time_base_seconds seconds, time_base_seconds useconds): Timeval(seconds, useconds) {} };DelayInterval 類基本上就是 Timeval 類的別名,而之所以重新定義這樣一個類,大概主要是為了便于閱讀維護吧。Timeval 類用標準庫中保存時間的 struct timeval 結構保存時間值,但通過操作符重載,提供了一些方便操作時間值的操作符函數。以成員函數的方式定義的操作符函數的實現如下:
int Timeval::operator>=(const Timeval& arg2) const {return seconds() > arg2.seconds()|| (seconds() == arg2.seconds()&& useconds() >= arg2.useconds()); }void Timeval::operator+=(const DelayInterval& arg2) {secs() += arg2.seconds(); usecs() += arg2.useconds();if (useconds() >= MILLION) {usecs() -= MILLION;++secs();} }void Timeval::operator-=(const DelayInterval& arg2) {secs() -= arg2.seconds(); usecs() -= arg2.useconds();if ((int)useconds() < 0) {usecs() += MILLION;--secs();}if ((int)seconds() < 0)secs() = usecs() = 0;}這些操作符函數的實現,都比較直觀。
除了以成員操作符函數定義的這些操作符之外,還包括如下這些非成員函數的操作符:
#ifndef max inline Timeval max(Timeval const& arg1, Timeval const& arg2) {return arg1 >= arg2 ? arg1 : arg2; } #endif #ifndef min inline Timeval min(Timeval const& arg1, Timeval const& arg2) {return arg1 <= arg2 ? arg1 : arg2; } #endif . . . . . . DelayInterval operator-(const Timeval& arg1, const Timeval& arg2) {time_base_seconds secs = arg1.seconds() - arg2.seconds();time_base_seconds usecs = arg1.useconds() - arg2.useconds();if ((int)usecs < 0) {usecs += MILLION;--secs;}if ((int)secs < 0)return DELAY_ZERO;elsereturn DelayInterval(secs, usecs); }///// DelayInterval /////DelayInterval operator*(short arg1, const DelayInterval& arg2) {time_base_seconds result_seconds = arg1*arg2.seconds();time_base_seconds result_useconds = arg1*arg2.useconds();time_base_seconds carry = result_useconds/MILLION;result_useconds -= carry*MILLION;result_seconds += carry;return DelayInterval(result_seconds, result_useconds); }#ifndef INT_MAX #define INT_MAX 0x7FFFFFFF #endif const DelayInterval DELAY_ZERO(0, 0); const DelayInterval DELAY_SECOND(1, 0); const DelayInterval DELAY_MINUTE = 60*DELAY_SECOND; const DelayInterval DELAY_HOUR = 60*DELAY_MINUTE; const DelayInterval DELAY_DAY = 24*DELAY_HOUR; const DelayInterval ETERNITY(INT_MAX, MILLION-1); // used internally to make the implementation work它們的實現也都比較直觀。
延遲任務的表示及組織
在 live555 的 BasicUsageEnvironment 模塊中,用 DelayQueueEntry 類表示一個延遲任務。該類定義如下:
class DelayQueueEntry { public:virtual ~DelayQueueEntry();intptr_t token() {return fToken;}protected: // abstract base classDelayQueueEntry(DelayInterval delay);virtual void handleTimeout();private:friend class DelayQueue;DelayQueueEntry* fNext;DelayQueueEntry* fPrev;DelayInterval fDeltaTimeRemaining;intptr_t fToken;static intptr_t tokenCounter; };延遲任務通過 token 來標識,token 在對象創建時,借助于全局的 tokenCounter 產生。fDeltaTimeRemaining 用于表示延遲任務需要被執行的時間距當前時間的間隔。由 fNext 和 fPrev 不難猜到,在 BasicUsageEnvironment 模塊中是以雙向鏈表來組織延遲任務的。handleTimeout() 函數是延遲任務的主體,需要由具體的子類提供實現。
DelayQueueEntry 類的具體實現如下:
intptr_t DelayQueueEntry::tokenCounter = 0;DelayQueueEntry::DelayQueueEntry(DelayInterval delay): fDeltaTimeRemaining(delay) {fNext = fPrev = this;fToken = ++tokenCounter; }DelayQueueEntry::~DelayQueueEntry() { }void DelayQueueEntry::handleTimeout() {delete this; }BasicUsageEnvironment 模塊中實際使用 AlarmHandler 來描述延遲任務的,其定義如下:
class AlarmHandler: public DelayQueueEntry { public:AlarmHandler(TaskFunc* proc, void* clientData, DelayInterval timeToDelay): DelayQueueEntry(timeToDelay), fProc(proc), fClientData(clientData) {}private: // redefined virtual functionsvirtual void handleTimeout() {(*fProc)(fClientData);DelayQueueEntry::handleTimeout();}private:TaskFunc* fProc;void* fClientData; };BasicUsageEnvironment 模塊需要用 DelayQueueEntry 類表示和組織延遲任務,而在接口層,也就是 TaskScheduler 中則是通過 TaskFunc 和用戶數據指針來表示延遲任務。AlarmHandler 協助完成接口的結構到實現的結構的轉換。
BasicUsageEnvironment 模塊使用 DelayQueue 把 DelayQueueEntry 組織為雙向鏈表,該類定義如下:
class DelayQueue: public DelayQueueEntry { public:DelayQueue();virtual ~DelayQueue();void addEntry(DelayQueueEntry* newEntry); // returns a token for the entryvoid updateEntry(DelayQueueEntry* entry, DelayInterval newDelay);void updateEntry(intptr_t tokenToFind, DelayInterval newDelay);void removeEntry(DelayQueueEntry* entry); // but doesn't delete itDelayQueueEntry* removeEntry(intptr_t tokenToFind); // but doesn't delete itDelayInterval const& timeToNextAlarm();void handleAlarm();private:DelayQueueEntry* head() { return fNext; }DelayQueueEntry* findEntryByToken(intptr_t token);void synchronize(); // bring the 'time remaining' fields up-to-date_EventTime fLastSyncTime; };首先來看一下 DelayQueue 類對象構造和銷毀的過程:
DelayQueue::DelayQueue(): DelayQueueEntry(ETERNITY) {fLastSyncTime = TimeNow(); }DelayQueue::~DelayQueue() {while (fNext != this) {DelayQueueEntry* entryToRemove = fNext;removeEntry(entryToRemove);delete entryToRemove;} }然后來看一下向鏈表中添加元素的過程:
void DelayQueue::addEntry(DelayQueueEntry* newEntry) {synchronize();DelayQueueEntry* cur = head();while (newEntry->fDeltaTimeRemaining >= cur->fDeltaTimeRemaining) {newEntry->fDeltaTimeRemaining -= cur->fDeltaTimeRemaining;cur = cur->fNext;}cur->fDeltaTimeRemaining -= newEntry->fDeltaTimeRemaining;// Add "newEntry" to the queue, just before "cur":newEntry->fNext = cur;newEntry->fPrev = cur->fPrev;cur->fPrev = newEntry->fPrev->fNext = newEntry; } . . . . . . void DelayQueue::synchronize() {// First, figure out how much time has elapsed since the last sync:_EventTime timeNow = TimeNow();if (timeNow < fLastSyncTime) {// The system clock has apparently gone back in time; reset our sync time and return:fLastSyncTime = timeNow;return;}DelayInterval timeSinceLastSync = timeNow - fLastSyncTime;fLastSyncTime = timeNow;// Then, adjust the delay queue for any entries whose time is up:DelayQueueEntry* curEntry = head();while (timeSinceLastSync >= curEntry->fDeltaTimeRemaining) {timeSinceLastSync -= curEntry->fDeltaTimeRemaining;curEntry->fDeltaTimeRemaining = DELAY_ZERO;curEntry = curEntry->fNext;}curEntry->fDeltaTimeRemaining -= timeSinceLastSync; }通過這兩個函數,可以更加清楚的看到,在 DelayQueue 中是怎么組織延遲任務的。DelayQueue 因為其本身是一個 DelayQueueEntry,實際上它是一個環形雙向鏈表。它的 fNext 指向這個鏈表的邏輯上的頭部元素,但它本身是這個鏈表的尾部元素。雙向鏈表中每個元素的 fDeltaTimeRemaining 保存的是這個任務應該被調度執行的時間點,與它前面的那個任務應該被調度執行的時間點之間的差值,當該值為 0 時,也就表示這個任務需要被執行了。這樣也就是說, DelayQueue 是一個雙向環形的有序鏈表,順序按照所需的執行時間排列。
removeEntry() 用于從雙向鏈表中移除一個任務:
void DelayQueue::removeEntry(DelayQueueEntry* entry) {if (entry == NULL || entry->fNext == NULL) return;entry->fNext->fDeltaTimeRemaining += entry->fDeltaTimeRemaining;entry->fPrev->fNext = entry->fNext;entry->fNext->fPrev = entry->fPrev;entry->fNext = entry->fPrev = NULL;// in case we should try to remove it again }DelayQueueEntry* DelayQueue::removeEntry(intptr_t tokenToFind) {DelayQueueEntry* entry = findEntryByToken(tokenToFind);removeEntry(entry);return entry; } . . . . . . DelayQueueEntry* DelayQueue::findEntryByToken(intptr_t tokenToFind) {DelayQueueEntry* cur = head();while (cur != this) {if (cur->token() == tokenToFind) return cur;cur = cur->fNext;}return NULL; }removeEntry(DelayQueueEntry* entry) 中,在 entry->fNext == NULL 成立時會直接返回,也是由于 DelayQueue 實際是一個雙向環形鏈表的緣故。
DelayQueue 還提供了用于更新延遲任務執行時間的接口:
void DelayQueue::updateEntry(DelayQueueEntry* entry, DelayInterval newDelay) {if (entry == NULL) return;removeEntry(entry);entry->fDeltaTimeRemaining = newDelay;addEntry(entry); }void DelayQueue::updateEntry(intptr_t tokenToFind, DelayInterval newDelay) {DelayQueueEntry* entry = findEntryByToken(tokenToFind);updateEntry(entry, newDelay); }此外,timeToNextAlarm() 用于計算最近的一個任務執行的時間,而 handleAlarm() 則用于執行該任務。
DelayInterval const& DelayQueue::timeToNextAlarm() {if (head()->fDeltaTimeRemaining == DELAY_ZERO) return DELAY_ZERO; // a common casesynchronize();return head()->fDeltaTimeRemaining; }void DelayQueue::handleAlarm() {if (head()->fDeltaTimeRemaining != DELAY_ZERO) synchronize();if (head()->fDeltaTimeRemaining == DELAY_ZERO) {// This event is due to be handled:DelayQueueEntry* toRemove = head();removeEntry(toRemove); // do this first, in case handler accesses queuetoRemove->handleTimeout();} }延遲任務調度
看過了 live555 的 BasicUsageEnvironment 模塊中時間的表示,以及延遲任務的表示及組織之后,再來看延遲任務的調度。
BasicTaskScheduler0 類通過 scheduleDelayedTask() 和 unscheduleDelayedTask() 函數實現定時器任務調度,它們分別用于調度一個延遲任務及取消一個延遲任務,它們的實現如下:
TaskToken BasicTaskScheduler0::scheduleDelayedTask(int64_t microseconds,TaskFunc* proc,void* clientData) {if (microseconds < 0) microseconds = 0;DelayInterval timeToDelay((long)(microseconds/1000000), (long)(microseconds%1000000));AlarmHandler* alarmHandler = new AlarmHandler(proc, clientData, timeToDelay);fDelayQueue.addEntry(alarmHandler);return (void*)(alarmHandler->token()); }void BasicTaskScheduler0::unscheduleDelayedTask(TaskToken& prevTask) {DelayQueueEntry* alarmHandler = fDelayQueue.removeEntry((intptr_t)prevTask);prevTask = NULL;delete alarmHandler; }延遲任務調度也就是把延遲任務放進 DelayQueue 中,而取消延遲任務則是,把任務從 DelayQueue 中移除。
后面再來看延遲任務被執行的過程。
用戶事件任務調度
用戶事件任務調度接口,讓調用者可以創建任務,并觸發該任務在事件循環中執行。這組接口主要包括這樣幾個:createEventTrigger()、deleteEventTrigger() 和 triggerEvent(),它們分別用于創建任務,刪除任務,及觸發任務執行。
這些接口的實現如下:
EventTriggerId BasicTaskScheduler0::createEventTrigger(TaskFunc* eventHandlerProc) {unsigned i = fLastUsedTriggerNum;EventTriggerId mask = fLastUsedTriggerMask;do {i = (i+1)%MAX_NUM_EVENT_TRIGGERS;mask >>= 1;if (mask == 0) mask = 0x80000000;if (fTriggeredEventHandlers[i] == NULL) {// This trigger number is free; use it:fTriggeredEventHandlers[i] = eventHandlerProc;fTriggeredEventClientDatas[i] = NULL; // sanityfLastUsedTriggerMask = mask;fLastUsedTriggerNum = i;return mask;}} while (i != fLastUsedTriggerNum);// All available event triggers are allocated; return 0 instead:return 0; }void BasicTaskScheduler0::deleteEventTrigger(EventTriggerId eventTriggerId) {fTriggersAwaitingHandling &=~ eventTriggerId;if (eventTriggerId == fLastUsedTriggerMask) { // common-case optimization:fTriggeredEventHandlers[fLastUsedTriggerNum] = NULL;fTriggeredEventClientDatas[fLastUsedTriggerNum] = NULL;} else {// "eventTriggerId" should have just one bit set.// However, we do the reasonable thing if the user happened to 'or' together two or more "EventTriggerId"s:EventTriggerId mask = 0x80000000;for (unsigned i = 0; i < MAX_NUM_EVENT_TRIGGERS; ++i) {if ((eventTriggerId&mask) != 0) {fTriggeredEventHandlers[i] = NULL;fTriggeredEventClientDatas[i] = NULL;}mask >>= 1;}} }void BasicTaskScheduler0::triggerEvent(EventTriggerId eventTriggerId, void* clientData) {// First, record the "clientData". (Note that we allow "eventTriggerId" to be a combination of bits for multiple events.)EventTriggerId mask = 0x80000000;for (unsigned i = 0; i < MAX_NUM_EVENT_TRIGGERS; ++i) {if ((eventTriggerId&mask) != 0) {fTriggeredEventClientDatas[i] = clientData;}mask >>= 1;}// Then, note this event as being ready to be handled.// (Note that because this function (unlike others in the library) can be called from an external thread, we do this last, to// reduce the risk of a race condition.)fTriggersAwaitingHandling |= eventTriggerId; }BasicTaskScheduler0 的 fTriggeredEventHandlers 和 fTriggeredEventClientDatas 用于保存任務本身,它們分別保存任務主體函數,以及執行任務時傳入的用戶數據。它們都是數組,每個任務占用一個元素,相同索引處的元素屬于同一個任務。數組的長度為 MAX_NUM_EVENT_TRIGGERS,即 32,也就是說最多可以創建的任務的個數為 32。
fTriggersAwaitingHandling 用于記錄當前觸發了哪些任務。每個任務的觸發狀態都對應于其中的一個位,當對應的位置 1 時,表示任務被觸發,需要執行;反之則不需要執行。比如 fTriggeredEventHandlers 和 fTriggeredEventClientDatas 中索引 0 處的任務的觸發狀態,對應于 fTriggersAwaitingHandling 的最高位,索引 1 處的任務的觸發狀態,對應于次高位,依次類推。
創建任務,即是在 fTriggeredEventHandlers 和 fTriggeredEventClientDatas 中為任務找到一個空閑的位置,把任務的主體函數的指針保存起來,返回任務的索引在 fTriggersAwaitingHandling 中的對應位的掩碼,作為任務的標識。fLastUsedTriggerNum 用于防止遍歷 fTriggeredEventHandlers 查找時的無限循環。
刪除任務即是移除任務相關的所有數據,包括復位 fTriggersAwaitingHandling 中的觸發狀態,以及 fTriggeredEventHandlers 和 fTriggeredEventClientDatas 中任務的主體函數指針和用戶數據。
觸發事件任務則是置為任務在 fTriggersAwaitingHandling 中對應的位,并設置任務數據。任務的實際執行同樣需要在事件循環中執行。
事件循環執行框架
BasicTaskScheduler0 中執行事件循環由 doEventLoop() 函數完成,具體實現如下:
void BasicTaskScheduler0::doEventLoop(char volatile* watchVariable) {// Repeatedly loop, handling readble sockets and timed events:while (1) {if (watchVariable != NULL && *watchVariable != 0) break;SingleStep();} }主要特別關注的是傳入的參數 watchVariable:調用者可以通過這個參數,來在事件循環的外部控制,事件循環何時結束。
Socket I/O 事件描述及其組織
BasicUsageEnvironment 模塊中,用 HandlerDescriptor 描述要監聽的 socket 上的事件及事件發生時的處理程序,該類定義如下:
class HandlerDescriptor {HandlerDescriptor(HandlerDescriptor* nextHandler);virtual ~HandlerDescriptor();public:int socketNum;int conditionSet;TaskScheduler::BackgroundHandlerProc* handlerProc;void* clientData;private:// Descriptors are linked together in a doubly-linked list:friend class HandlerSet;friend class HandlerIterator;HandlerDescriptor* fNextHandler;HandlerDescriptor* fPrevHandler; };socketNum 為要監聽的 socket,conditionSet 描述要監聽的 socket 上的事件,handlerProc 為事件發生時的處理程序,clientData 為傳遞給事件處理程序的用戶數據。而 fNextHandler 和 fPrevHandler 則用于將
HandlerDescriptor 組織起來。不難猜到,BasicUsageEnvironment 模塊中 HandlerDescriptor 也是要被組織為雙向鏈表的。
HandlerDescriptor 類的實現如下:
HandlerDescriptor::HandlerDescriptor(HandlerDescriptor* nextHandler): conditionSet(0), handlerProc(NULL) {// Link this descriptor into a doubly-linked list:if (nextHandler == this) { // initializationfNextHandler = fPrevHandler = this;} else {fNextHandler = nextHandler;fPrevHandler = nextHandler->fPrevHandler;nextHandler->fPrevHandler = this;fPrevHandler->fNextHandler = this;} }HandlerDescriptor::~HandlerDescriptor() {// Unlink this descriptor from a doubly-linked list:fNextHandler->fPrevHandler = fPrevHandler;fPrevHandler->fNextHandler = fNextHandler; }BasicUsageEnvironment 模塊中,使用 HandlerSet 來維護所有的 HandlerDescriptor,這個類的定義如下:
class HandlerSet { public:HandlerSet();virtual ~HandlerSet();void assignHandler(int socketNum, int conditionSet, TaskScheduler::BackgroundHandlerProc* handlerProc, void* clientData);void clearHandler(int socketNum);void moveHandler(int oldSocketNum, int newSocketNum);private:HandlerDescriptor* lookupHandler(int socketNum);private:friend class HandlerIterator;HandlerDescriptor fHandlers; };HandlerSet/HandlerDescriptor 的設計與 DelayQueue/DelayQueueEntry 的設計非常相似。HandlerSet 的實現如下:
HandlerSet::HandlerSet(): fHandlers(&fHandlers) {fHandlers.socketNum = -1; // shouldn't ever get looked at, but in case... }HandlerSet::~HandlerSet() {// Delete each handler descriptor:while (fHandlers.fNextHandler != &fHandlers) {delete fHandlers.fNextHandler; // changes fHandlers->fNextHandler} }void HandlerSet ::assignHandler(int socketNum, int conditionSet, TaskScheduler::BackgroundHandlerProc* handlerProc, void* clientData) {// First, see if there's already a handler for this socket:HandlerDescriptor* handler = lookupHandler(socketNum);if (handler == NULL) { // No existing handler, so create a new descr:handler = new HandlerDescriptor(fHandlers.fNextHandler);handler->socketNum = socketNum;}handler->conditionSet = conditionSet;handler->handlerProc = handlerProc;handler->clientData = clientData; }void HandlerSet::clearHandler(int socketNum) {HandlerDescriptor* handler = lookupHandler(socketNum);delete handler; }void HandlerSet::moveHandler(int oldSocketNum, int newSocketNum) {HandlerDescriptor* handler = lookupHandler(oldSocketNum);if (handler != NULL) {handler->socketNum = newSocketNum;} }HandlerDescriptor* HandlerSet::lookupHandler(int socketNum) {HandlerDescriptor* handler;HandlerIterator iter(*this);while ((handler = iter.next()) != NULL) {if (handler->socketNum == socketNum) break;}return handler; }HandlerSet 類似地,被設計為 HandlerDescriptor 的雙向循環列表,只是其中的元素的順序沒有意義。
BasicUsageEnvironment 模塊還提供了迭代器 HandlerIterator,用于遍歷HandlerSet ,其定義及實現如下:
class HandlerIterator { public:HandlerIterator(HandlerSet& handlerSet);virtual ~HandlerIterator();HandlerDescriptor* next(); // returns NULL if nonevoid reset();private:HandlerSet& fOurSet;HandlerDescriptor* fNextPtr; };///////////////////////////////////// Implementation HandlerIterator::HandlerIterator(HandlerSet& handlerSet): fOurSet(handlerSet) {reset(); }HandlerIterator::~HandlerIterator() { }void HandlerIterator::reset() {fNextPtr = fOurSet.fHandlers.fNextHandler; }HandlerDescriptor* HandlerIterator::next() {HandlerDescriptor* result = fNextPtr;if (result == &fOurSet.fHandlers) { // no moreresult = NULL;} else {fNextPtr = fNextPtr->fNextHandler;}return result; }總結一下,可以監聽每個 socket 上的事件,并在事件發生時執行處理程序,監聽的 socket 上的事件及事件處理程序由 HandlerDescriptor 描述;所有的 HandlerDescriptor 由 HandlerSet 組織為一個雙向的循環鏈表,元素之間的實際順序沒有意義,新加入的元素被放在邏輯上的鏈表頭部。
Socket I/O 事件處理任務調度
Socket I/O 事件處理任務調度都在 BasicTaskScheduler 類中完成,這個類的定義如下:
class BasicTaskScheduler: public BasicTaskScheduler0 { public:static BasicTaskScheduler* createNew(unsigned maxSchedulerGranularity = 10000/*microseconds*/);virtual ~BasicTaskScheduler();protected:BasicTaskScheduler(unsigned maxSchedulerGranularity);// called only by "createNew()"static void schedulerTickTask(void* clientData);void schedulerTickTask();protected:// Redefined virtual functions:virtual void SingleStep(unsigned maxDelayTime);virtual void setBackgroundHandling(int socketNum, int conditionSet, BackgroundHandlerProc* handlerProc, void* clientData);virtual void moveSocketHandling(int oldSocketNum, int newSocketNum);protected:// To implement background reads:HandlerSet* fHandlers;int fLastHandledSocketNum;unsigned fMaxSchedulerGranularity;// To implement background operations:int fMaxNumSockets;fd_set fReadSet;fd_set fWriteSet;fd_set fExceptionSet; . . . . . . };fHandlers 用于組織 HandlerDescriptor,fReadSet、fWriteSet、fExceptionSet 和 fMaxNumSockets 主要是為了適配 select() 接口,分別用于描述要監聽其可讀事件、可寫事件、異常事件的 socket 集合,以及要監聽的 socket 中 socket number 最大的那個。
Socket I/O 事件處理任務調度,由 setBackgroundHandling() 和 moveSocketHandling() 這兩個函數完成,它們的實現如下:
void BasicTaskScheduler::setBackgroundHandling(int socketNum, int conditionSet, BackgroundHandlerProc* handlerProc, void* clientData) {if (socketNum < 0) return; #if !defined(__WIN32__) && !defined(_WIN32) && defined(FD_SETSIZE)if (socketNum >= (int)(FD_SETSIZE)) return; #endifFD_CLR((unsigned)socketNum, &fReadSet);FD_CLR((unsigned)socketNum, &fWriteSet);FD_CLR((unsigned)socketNum, &fExceptionSet);if (conditionSet == 0) {fHandlers->clearHandler(socketNum);if (socketNum+1 == fMaxNumSockets) {--fMaxNumSockets;}} else {fHandlers->assignHandler(socketNum, conditionSet, handlerProc, clientData);if (socketNum+1 > fMaxNumSockets) {fMaxNumSockets = socketNum+1;}if (conditionSet&SOCKET_READABLE) FD_SET((unsigned)socketNum, &fReadSet);if (conditionSet&SOCKET_WRITABLE) FD_SET((unsigned)socketNum, &fWriteSet);if (conditionSet&SOCKET_EXCEPTION) FD_SET((unsigned)socketNum, &fExceptionSet);} }void BasicTaskScheduler::moveSocketHandling(int oldSocketNum, int newSocketNum) {if (oldSocketNum < 0 || newSocketNum < 0) return; // sanity check #if !defined(__WIN32__) && !defined(_WIN32) && defined(FD_SETSIZE)if (oldSocketNum >= (int)(FD_SETSIZE) || newSocketNum >= (int)(FD_SETSIZE)) return; // sanity check #endifif (FD_ISSET(oldSocketNum, &fReadSet)) {FD_CLR((unsigned)oldSocketNum, &fReadSet); FD_SET((unsigned)newSocketNum, &fReadSet);}if (FD_ISSET(oldSocketNum, &fWriteSet)) {FD_CLR((unsigned)oldSocketNum, &fWriteSet); FD_SET((unsigned)newSocketNum, &fWriteSet);}if (FD_ISSET(oldSocketNum, &fExceptionSet)) {FD_CLR((unsigned)oldSocketNum, &fExceptionSet); FD_SET((unsigned)newSocketNum, &fExceptionSet);}fHandlers->moveHandler(oldSocketNum, newSocketNum);if (oldSocketNum+1 == fMaxNumSockets) {--fMaxNumSockets;}if (newSocketNum+1 > fMaxNumSockets) {fMaxNumSockets = newSocketNum+1;} }對于 setBackgroundHandling(),當 conditionSet 為非 0 值時,會更新或者新建對特定 socket 的監聽;為 0 時,則將清除對該 socket 的監聽。 moveSocketHandling() 更新對于 socket 事件的監聽。
BasicTaskScheduler 的 SingleStep() 實現事件循環的單次迭代:
void BasicTaskScheduler::SingleStep(unsigned maxDelayTime) {fd_set readSet = fReadSet; // make a copy for this select() callfd_set writeSet = fWriteSet; // dittofd_set exceptionSet = fExceptionSet; // dittoDelayInterval const& timeToDelay = fDelayQueue.timeToNextAlarm();struct timeval tv_timeToDelay;tv_timeToDelay.tv_sec = timeToDelay.seconds();tv_timeToDelay.tv_usec = timeToDelay.useconds();// Very large "tv_sec" values cause select() to fail.// Don't make it any larger than 1 million seconds (11.5 days)const long MAX_TV_SEC = MILLION;if (tv_timeToDelay.tv_sec > MAX_TV_SEC) {tv_timeToDelay.tv_sec = MAX_TV_SEC;}// Also check our "maxDelayTime" parameter (if it's > 0):if (maxDelayTime > 0 &&(tv_timeToDelay.tv_sec > (long)maxDelayTime/MILLION ||(tv_timeToDelay.tv_sec == (long)maxDelayTime/MILLION &&tv_timeToDelay.tv_usec > (long)maxDelayTime%MILLION))) {tv_timeToDelay.tv_sec = maxDelayTime/MILLION;tv_timeToDelay.tv_usec = maxDelayTime%MILLION;}int selectResult = select(fMaxNumSockets, &readSet, &writeSet, &exceptionSet, &tv_timeToDelay);if (selectResult < 0) { #if defined(__WIN32__) || defined(_WIN32)int err = WSAGetLastError();// For some unknown reason, select() in Windoze sometimes fails with WSAEINVAL if// it was called with no entries set in "readSet". If this happens, ignore it:if (err == WSAEINVAL && readSet.fd_count == 0) {err = EINTR;// To stop this from happening again, create a dummy socket:if (fDummySocketNum >= 0) closeSocket(fDummySocketNum);fDummySocketNum = socket(AF_INET, SOCK_DGRAM, 0);FD_SET((unsigned)fDummySocketNum, &fReadSet);}if (err != EINTR) { #elseif (errno != EINTR && errno != EAGAIN) { #endif// Unexpected error - treat this as fatal: #if !defined(_WIN32_WCE)perror("BasicTaskScheduler::SingleStep(): select() fails");// Because this failure is often "Bad file descriptor" - which is caused by an invalid socket number (i.e., a socket number// that had already been closed) being used in "select()" - we print out the sockets that were being used in "select()",// to assist in debugging:fprintf(stderr, "socket numbers used in the select() call:");for (int i = 0; i < 10000; ++i) {if (FD_ISSET(i, &fReadSet) || FD_ISSET(i, &fWriteSet) || FD_ISSET(i, &fExceptionSet)) {fprintf(stderr, " %d(", i);if (FD_ISSET(i, &fReadSet)) fprintf(stderr, "r");if (FD_ISSET(i, &fWriteSet)) fprintf(stderr, "w");if (FD_ISSET(i, &fExceptionSet)) fprintf(stderr, "e");fprintf(stderr, ")");}}fprintf(stderr, "\n"); #endifinternalError();}}// Call the handler function for one readable socket:HandlerIterator iter(*fHandlers);HandlerDescriptor* handler;// To ensure forward progress through the handlers, begin past the last// socket number that we handled:if (fLastHandledSocketNum >= 0) {while ((handler = iter.next()) != NULL) {if (handler->socketNum == fLastHandledSocketNum) break;}if (handler == NULL) {fLastHandledSocketNum = -1;iter.reset(); // start from the beginning instead}}while ((handler = iter.next()) != NULL) {int sock = handler->socketNum; // aliasint resultConditionSet = 0;if (FD_ISSET(sock, &readSet) && FD_ISSET(sock, &fReadSet)/*sanity check*/) resultConditionSet |= SOCKET_READABLE;if (FD_ISSET(sock, &writeSet) && FD_ISSET(sock, &fWriteSet)/*sanity check*/) resultConditionSet |= SOCKET_WRITABLE;if (FD_ISSET(sock, &exceptionSet) && FD_ISSET(sock, &fExceptionSet)/*sanity check*/) resultConditionSet |= SOCKET_EXCEPTION;if ((resultConditionSet&handler->conditionSet) != 0 && handler->handlerProc != NULL) {fLastHandledSocketNum = sock;// Note: we set "fLastHandledSocketNum" before calling the handler,// in case the handler calls "doEventLoop()" reentrantly.(*handler->handlerProc)(handler->clientData, resultConditionSet);break;}}if (handler == NULL && fLastHandledSocketNum >= 0) {// We didn't call a handler, but we didn't get to check all of them,// so try again from the beginning:iter.reset();while ((handler = iter.next()) != NULL) {int sock = handler->socketNum; // aliasint resultConditionSet = 0;if (FD_ISSET(sock, &readSet) && FD_ISSET(sock, &fReadSet)/*sanity check*/) resultConditionSet |= SOCKET_READABLE;if (FD_ISSET(sock, &writeSet) && FD_ISSET(sock, &fWriteSet)/*sanity check*/) resultConditionSet |= SOCKET_WRITABLE;if (FD_ISSET(sock, &exceptionSet) && FD_ISSET(sock, &fExceptionSet)/*sanity check*/) resultConditionSet |= SOCKET_EXCEPTION;if ((resultConditionSet&handler->conditionSet) != 0 && handler->handlerProc != NULL) {fLastHandledSocketNum = sock;// Note: we set "fLastHandledSocketNum" before calling the handler,// in case the handler calls "doEventLoop()" reentrantly.(*handler->handlerProc)(handler->clientData, resultConditionSet);break;}}if (handler == NULL) fLastHandledSocketNum = -1;//because we didn't call a handler}// Also handle any newly-triggered event (Note that we do this *after* calling a socket handler,// in case the triggered event handler modifies The set of readable sockets.)if (fTriggersAwaitingHandling != 0) {if (fTriggersAwaitingHandling == fLastUsedTriggerMask) {// Common-case optimization for a single event trigger:fTriggersAwaitingHandling &=~ fLastUsedTriggerMask;if (fTriggeredEventHandlers[fLastUsedTriggerNum] != NULL) {(*fTriggeredEventHandlers[fLastUsedTriggerNum])(fTriggeredEventClientDatas[fLastUsedTriggerNum]);}} else {// Look for an event trigger that needs handling (making sure that we make forward progress through all possible triggers):unsigned i = fLastUsedTriggerNum;EventTriggerId mask = fLastUsedTriggerMask;do {i = (i+1)%MAX_NUM_EVENT_TRIGGERS;mask >>= 1;if (mask == 0) mask = 0x80000000;if ((fTriggersAwaitingHandling&mask) != 0) {fTriggersAwaitingHandling &=~ mask;if (fTriggeredEventHandlers[i] != NULL) {(*fTriggeredEventHandlers[i])(fTriggeredEventClientDatas[i]);}fLastUsedTriggerMask = mask;fLastUsedTriggerNum = i;break;}} while (i != fLastUsedTriggerNum);}}// Also handle any delayed event that may have come due.fDelayQueue.handleAlarm(); }這個函數有點長,但清晰地分為如下幾個部分:
1. 根據定時器任務列表中,距當前時間最近的任務所需執行的時間點以及傳入的最大延遲時間,計算 select() 所能夠等待地最長時間。
2. 執行 select() 等待 socket 上的時間。
3. select() 超時或某個 socket 上的 I/O 事件到來,首先執行發生 I/O 事件的 socket 的 I/O 事件處理程序。這個函數一次最多執行一個 socket 上的 I/O 處理程序。
4. 執行用戶事件處理程序。也是一次最多執行一個。
5. 執行定時器任務,同樣是一次最多執行一個。
live555 的基礎設施基本上就是這些了。
live555 源碼分析系列文章
live555 源碼分析:簡介
live555 源碼分析:基礎設施
總結
以上是生活随笔為你收集整理的live555 源码分析:基础设施的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: live555 源码分析:简介
- 下一篇: live555 源码分析:MediaSe