live555 源码分析:基础设施
live555 由多個(gè)模塊組成,其中 UsageEnvironment 、 BasicUsageEnvironment 和 groupsock 分別提供了事件循環(huán),輸入輸出,基本的數(shù)據(jù)結(jié)構(gòu),以及網(wǎng)絡(luò) IO 等功能,它們可以看作 live555 的基礎(chǔ)設(shè)施。對(duì)于 live555 的源碼分析,就從這些基礎(chǔ)設(shè)施,基本的數(shù)據(jù)結(jié)構(gòu)開(kāi)始。
HashTable
首先來(lái)看 HashTable,這是 live555 定義的一個(gè)范型關(guān)聯(lián)容器。
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 要定義為范型關(guān)聯(lián)容器,然而它沒(méi)有使用 C++ 的模板。HashTable 要求鍵為一個(gè) C 風(fēng)格的字符串,即 char const*,而值為一個(gè) void*,以此可以表示各種不同類型的值。就像 C++ 標(biāo)準(zhǔn)庫(kù)中的許多容器一眼,HashTable 內(nèi)部還定義了一個(gè)迭代器類,用來(lái)遍歷這個(gè)容器。
其它添加、移除、查找元素等操作,與其它的普通容器設(shè)計(jì)并沒(méi)有太大的不同。
HashTable 類實(shí)現(xiàn)了公共的與具體存儲(chǔ)結(jié)構(gòu)無(wú)關(guān)的兩個(gè)模板函數(shù) RemoveNext() 和 getFirst(),這兩個(gè)函數(shù)分別用于移除容器中的下一個(gè)元素并返回元素的值,及得到容器中的第一個(gè)元素,它們的實(shí)現(xiàn)如下:
#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; }這兩個(gè)函數(shù),都借助于容器的迭代器來(lái)實(shí)現(xiàn)。Iterator 類的 next(char const*& key) 接收一個(gè)傳出參數(shù),用于將鍵返回給調(diào)用者。
從接口定義的角度來(lái)看 live555 定義的 HashTable。它的 Iterator 類對(duì)象是由 Iterator 類的靜態(tài)方法 create(HashTable const& hashTable) 創(chuàng)建的,但銷毀創(chuàng)建的對(duì)象的職責(zé)卻是在調(diào)用者這里,這大大破壞了 HashTable 接口的實(shí)現(xiàn)的靈活性,比如創(chuàng)建的對(duì)象因此而無(wú)法做緩存。
HashTable 類及其迭代器類 Iterator 各自定義了一個(gè)靜態(tài)方法 create()。這里使用了橋接的方式,HashTable 的這個(gè)方法像一座橋一樣,把 HashTable 接口與接口的實(shí)現(xiàn)聯(lián)系了起來(lái)。這個(gè)類靜態(tài)函數(shù)都在實(shí)現(xiàn)接口的類中定義。
HashTable 有兩種類型,分別用兩個(gè)整型值來(lái)標(biāo)識(shí),STRING_HASH_KEYS 和 ONE_WORD_HASH_KEYS。當(dāng)然,依賴于在 create() 方法中是根據(jù) HashTable 類型創(chuàng)建相同類的對(duì)象還是創(chuàng)建不同類的對(duì)象,可以將 create() 方法的設(shè)計(jì)理解為是橋接,或者工廠方法。
BasicUsageEnvironment 的 BasicHashTable
BasicUsageEnvironment 中的 BasicHashTable 提供了一個(gè) HashTable 的實(shí)現(xiàn)。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 定義了一個(gè)類 TableEntry,用于表示鍵-值對(duì)。fNext 字段用于指向計(jì)算的鍵的哈希值沖突的不同的鍵-值對(duì)中的下一個(gè)。
來(lái)看 BasicHashTable 的創(chuàng)建:
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 指針的數(shù)組保存所有的鍵-值對(duì)。在該類對(duì)象創(chuàng)建時(shí),一個(gè)小的 TableEntry 指針數(shù)組 fStaticBuckets 會(huì)隨著對(duì)象的創(chuàng)建而創(chuàng)建,在 BasicHashTable 中元素比較少時(shí),直接在這個(gè)數(shù)組中保存鍵值對(duì),以此來(lái)優(yōu)化當(dāng)元素比較少的性能,降低內(nèi)存分配的開(kāi)銷。
fBuckets 指向保存鍵-值對(duì)的 TableEntry 指針數(shù)組,在對(duì)象創(chuàng)建初期,它指向 fStaticBuckets,而在哈希桶擴(kuò)容時(shí),它指向新分配的 TableEntry 指針數(shù)組。對(duì)于容器中元素的訪問(wèn),都通過(guò)
fBuckets 來(lái)完成。fNumBuckets 用于保存 TableEntry 指針數(shù)組的長(zhǎng)度。fNumEntries 用于保存容器中鍵-值對(duì)的個(gè)數(shù)。fRebuildSize 為哈希桶擴(kuò)容的閾值,即當(dāng) BasicHashTable 中保存的鍵值對(duì)超過(guò)該值時(shí),哈希桶需要擴(kuò)容。fDownShift 和 fMask 用于計(jì)算哈希值,并把哈希值映射到哈希桶容量范圍內(nèi)。
向 BasicHashTable 中插入元素
可以通過(guò) Add(char const* key, void* value) 向 BasicHashTable 中插入元素,這個(gè)函數(shù)的定義如下:
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 中插入元素的過(guò)車大致如下:
1. 查找 BasicHashTable 中與要插入的鍵-值對(duì)的鍵匹配的元素 TableEntry。
2. 若找到,把該元素的舊的值保存在 oldValue 中。
3. 若沒(méi)有找到,則通過(guò) insertNewEntry(index, key) 創(chuàng)建一個(gè) TableEntry 并加入到哈希桶中,oldValue 被賦值為 NULL。
4. 把要插入的鍵-值對(duì)的值保存進(jìn)新創(chuàng)建或找到的 TableEntry 中。
5. 如果 BasicHashTable 中的元素個(gè)數(shù)超出 fRebuildSize 的大小,則對(duì)哈希桶擴(kuò)容。
6. 返回元素的舊的值。
查找 BasicHashTable 中與要插入的鍵-值對(duì)的鍵匹配的元素 TableEntry 的過(guò)程如下:
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() 首先通過(guò) hashIndexFromKey(key) 根據(jù)鍵值對(duì)的鍵計(jì)算哈希值,并把該值映射到哈希桶容量范圍內(nèi),得到索引。然后根據(jù)得到的索引,查找與傳入的鍵匹配的元素。
這里可以更加清晰地看到,不同類型的 HashTable 之間的區(qū)別主要在于對(duì)待鍵的方式不同。STRING_HASH_KEYS 型的 HashTable,其鍵為傳入的字符串指針指向的字符串的內(nèi)容,而
ONE_WORD_HASH_KEYS 型的 HashTable,其鍵則為傳入的字符串指針本身。
計(jì)算最終的哈希值,并把該值映射到哈希桶容量范圍內(nèi),得到索引的過(guò)程如下:
unsigned randomIndex(uintptr_t i) const {return (unsigned)(((i*1103515245) >> fDownShift) & fMask);}insertNewEntry(index, key) 創(chuàng)建一個(gè) TableEntry 并加入到哈希桶中的過(guò)程如下:
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;} }可見(jiàn)插入的過(guò)程主要為,
1. 創(chuàng)建 TableEntry 對(duì)象,并把它插入到鍵所對(duì)應(yīng)的 TableEntry 指針數(shù)組中的 TableEntry 元素鏈的頭部。
2. 增加容器中元素個(gè)數(shù)的計(jì)數(shù)。
3. 為 TableEntry 分配傳入的鍵。
依據(jù) HashTable 類型的不同,分配鍵的方式也不同。
1. 對(duì)于 STRING_HASH_KEYS 型的 HashTable,需要將傳入的字符串指針指向的字符串的內(nèi)容復(fù)制一份,賦值給 TableEntry 的 key。
2. 對(duì)于 ONE_WORD_HASH_KEYS 型的 HashTable,需要將傳入的字符串指針本身,賦值給 TableEntry 的 key。
3. 對(duì)于 fKeyType 大于 0 的情況,需要將傳入的字符串指針指向的字符串的內(nèi)容的前 (sizeof(unsigned) * fKeyType) 個(gè)字節(jié)復(fù)制一份,賦值給 TableEntry 的 key。這種代碼真是看得人膽顫心驚,萬(wàn)一傳入的 key 字符串長(zhǎng)度小于 (sizeof(unsigned) * fKeyType) 個(gè)字節(jié)呢?。。。
對(duì)比 keyMatches() 和 assignKey() 函數(shù)的實(shí)現(xiàn),不難發(fā)現(xiàn),當(dāng) HashTable 類型 fKeyType 大于0,且不是 ONE_WORD_HASH_KEYS 時(shí),要求作為哈希表中鍵值對(duì)的鍵的字符串的長(zhǎng)度固定為 (sizeof(unsigned) * fKeyType) 個(gè)字節(jié)。
然后來(lái)看,BasicHashTable 中對(duì)哈希桶擴(kuò)容的過(guò)程:
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 分配一塊新的內(nèi)存,容量為原來(lái)的4倍。
2. 適當(dāng)更新 fNumBuckets,fRebuildSize,fDownShift 和 fMask 等。
3. 將老的 fBuckets 中的元素,依據(jù)元素的 key 和新的哈希桶的容量,搬到新的 fBuckets 中。
4. 根據(jù)需要釋放老的 fBuckets 的內(nèi)存。
在 BasicHashTable 中查找元素
然后來(lái)看在 BasicHashTable 中查找元素的過(guò)程:
void* BasicHashTable::Lookup(char const* key) const {unsigned index;TableEntry* entry = lookupKey(key, index);if (entry == NULL) return NULL; // no such entryreturn entry->value; }這個(gè)過(guò)程主要是根據(jù) key,通過(guò) lookupKey() 查找到對(duì)應(yīng)的元素 TableEntry,然后返回其 value。
移除 BasicHashTable 中的元素
來(lái)看移除 BasicHashTable 中的元素的過(guò)程:
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 中的元素的過(guò)程,也是免不了要先找到元素在 BasicHashTable 中的 TableEntry 的,找到之后,通過(guò) deleteEntry() 移除元素。
在 deleteEntry() 中,先把元素從 BasicHashTable 中移除出去,然后通過(guò) deleteKey() 釋放 key 占用的內(nèi)存,隨后釋放 TableEntry 本身占用的內(nèi)存。這里把 TableEntry 從 BasicHashTable 中移除出去采用了下面這種方法:
TableEntry** ep = &fBuckets[index];Boolean foundIt = False;while (*ep != NULL) {if (*ep == entry) {foundIt = True;*ep = entry->fNext;break;}ep = &((*ep)->fNext);}通過(guò)二級(jí)指針,遍歷鏈表一趟,就將元素移除出去了。記得這是這中場(chǎng)景下 Linus 大神鼓勵(lì)的一種寫(xiě)法。從鏈表中刪除一個(gè)元素,用好幾個(gè)臨時(shí)變量,或者加許多判斷的方法,都弱爆了。
通過(guò) Iterator 遍歷 BasicHashTable
可以使用 BasicHashTable 中定義的 Iterator 來(lái)遍歷它。過(guò)程如下:
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 中的每個(gè)元素都保存一個(gè) TableEntry 的鏈表。在這里會(huì)逐個(gè)鏈表地遍歷。
live555 定義的 HashTable 的內(nèi)容就是這些了。
UsageEnvironment
live555 中,UsageEnvironment 類扮演一個(gè)簡(jiǎn)單的控制器的角色。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 的操作,在發(fā)生內(nèi)部錯(cuò)誤時(shí)的處理程序 internalError(),以及銷毀自身的操作。UsageEnvironment 類本身實(shí)現(xiàn)了如下這幾個(gè)函數(shù):
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(); }這些函數(shù)都比較簡(jiǎn)單,這里不再贅述。
UsageEnvironment 是一個(gè)接口類,BasicUsageEnvironment 模塊中,通過(guò)兩個(gè)類 BasicUsageEnvironment 和 BasicUsageEnvironment0,提供了它的一個(gè)實(shí)現(xiàn)。BasicUsageEnvironment0 類提供了那組直接操作字符串的函數(shù)的實(shí)現(xiàn),該類的定義如下:
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; };這個(gè)類定義了一個(gè)緩沖區(qū),大小為 RESULT_MSG_BUFFER_MAX。類的實(shí)現(xiàn)如下:
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); }這組函數(shù)提供了把傳入的字符串,加進(jìn)緩沖區(qū),以及把緩沖區(qū)中的內(nèi)容輸出到標(biāo)準(zhǔn)輸出的功能。
BasicUsageEnvironment 類則提供了那組用于輸出基本數(shù)據(jù)類型的操作符。這個(gè)類的定義如下:
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(); };定義比較簡(jiǎn)單。然后來(lái)看它的實(shí)現(xiàn):
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 類還提供了一個(gè)靜態(tài)的創(chuàng)建對(duì)象的函數(shù) createNew() 用來(lái)創(chuàng)建 BasicUsageEnvironment 的對(duì)象。對(duì)于那些輸出操作符的實(shí)現(xiàn),都比較直接。
感覺(jué) live555 這組 I/O 函數(shù)的實(shí)現(xiàn)并不是太好,C++ 標(biāo)準(zhǔn)庫(kù)對(duì)這些接口都有著良好的實(shí)現(xiàn),但 live555 似乎并沒(méi)有要引入 C++ 標(biāo)準(zhǔn)庫(kù)的打算。
TaskScheduler
TaskScheduler 是 live555 中的任務(wù)調(diào)度器,它實(shí)現(xiàn)了 live555 的事件循環(huán)。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. 調(diào)度定時(shí)器任務(wù)。這主要包括 scheduleDelayedTask()、unscheduleDelayedTask() 和 rescheduleDelayedTask() 這幾個(gè)函數(shù),它們分別用于調(diào)度一個(gè)延遲任務(wù),取消一個(gè)延遲任務(wù),以及重新調(diào)度一個(gè)延遲任務(wù)。
2. 后臺(tái)調(diào)度 Socket I/O 處理操作。這主要包括 setBackgroundHandling()、disableBackgroundHandling()、moveSocketHandling()、turnOnBackgroundReadHandling() 和 turnOffBackgroundReadHandling() 這樣幾個(gè)函數(shù),它們用于設(shè)置、修改或取消 socket 上特定 I/O 事件的處理程序。
3. 用戶事件調(diào)度。這主要包括 createEventTrigger()、deleteEventTrigger() 和 triggerEvent() 這樣幾個(gè)函數(shù),它們用于創(chuàng)建、刪除及觸發(fā)一個(gè)用戶自定義事件。
4. 執(zhí)行事件循環(huán)。這個(gè)由 doEventLoop() 函數(shù)完成,這個(gè)函數(shù)通常也是應(yīng)用程序的主循環(huán)。
5. 內(nèi)部錯(cuò)誤處理程序。這個(gè)指 internalError() 函數(shù),用于在 TaskScheduler 發(fā)生內(nèi)部錯(cuò)誤時(shí),執(zhí)行一些處理。
TaskScheduler 類本身提供了幾個(gè)簡(jiǎn)單函數(shù)的實(shí)現(xiàn):
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(); }它們都簡(jiǎn)單而易于理解,這里不再贅述。
BasicUsageEnvironment 模塊中同樣提供了,TaskScheduler 接口的實(shí)現(xiàn)。與 UsageEnvironment 接口的情況類似,TaskScheduler 類的接口同樣由兩個(gè)類來(lái)實(shí)現(xiàn),分別是 BasicTaskScheduler 和 BasicTaskScheduler0,其中
BasicTaskScheduler0 類實(shí)現(xiàn)我們前面提到的第 1 組,第 3 組接口,以及 doEventLoop() 的框架,而 BasicTaskScheduler 則用于實(shí)現(xiàn)第 2 組接口,并實(shí)現(xiàn) doEventLoop() 的事件循環(huán)的循環(huán)體。
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 類的成員函數(shù),基本上就是繼承自 TaskScheduler 類中,它要實(shí)現(xiàn)功能的那部分接口,但它新添加了一個(gè)虛函數(shù) SingleStep() ,用于讓其子類覆寫(xiě),實(shí)現(xiàn)事件循環(huán)中的單次迭代。
BasicTaskScheduler0 類的成員變量則是清晰地分為三組:fDelayQueue 用于實(shí)現(xiàn)定時(shí)器操作;fHandlers 和 fLastHandledSocketNum 用于實(shí)現(xiàn) Socket I/O 事件處理操作;fTriggersAwaitingHandling、fLastUsedTriggerMask、fTriggeredEventHandlers、fTriggeredEventClientDatas 和 fLastUsedTriggerNum 用于實(shí)現(xiàn)用戶事件。
*對(duì)于 fHandlers 和 fLastHandledSocketNum,感覺(jué)實(shí)際上沒(méi)有必要在
BasicTaskScheduler0 類中定義。縱觀 BasicTaskScheduler0 類的整個(gè)實(shí)現(xiàn),除初始化這兩個(gè)成員變量之外,不存在其它的訪問(wèn)操作。從這兩個(gè)變量的職責(zé)來(lái)說(shuō),也不在 BasicTaskScheduler0 類的職責(zé)范圍內(nèi)。感覺(jué)這兩個(gè)變量實(shí)際上放在 BasicTaskScheduler 類中更合適一點(diǎn)。*
BasicTaskScheduler0 類對(duì)象創(chuàng)建及銷毀過(guò)程如下:
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; }在類對(duì)象創(chuàng)建的過(guò)程中,創(chuàng)建和/或初始化成員對(duì)象,對(duì)象銷毀時(shí),則銷毀成員對(duì)象。
時(shí)間的表示
在 live555 的 BasicUsageEnvironment 模塊中,用 Timeval 類來(lái)描述時(shí)間,并用 DelayInterval 來(lái)描述延遲時(shí)間。這兩個(gè)類的定義如下:
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 類的別名,而之所以重新定義這樣一個(gè)類,大概主要是為了便于閱讀維護(hù)吧。Timeval 類用標(biāo)準(zhǔn)庫(kù)中保存時(shí)間的 struct timeval 結(jié)構(gòu)保存時(shí)間值,但通過(guò)操作符重載,提供了一些方便操作時(shí)間值的操作符函數(shù)。以成員函數(shù)的方式定義的操作符函數(shù)的實(shí)現(xiàn)如下:
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;}這些操作符函數(shù)的實(shí)現(xiàn),都比較直觀。
除了以成員操作符函數(shù)定義的這些操作符之外,還包括如下這些非成員函數(shù)的操作符:
#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它們的實(shí)現(xiàn)也都比較直觀。
延遲任務(wù)的表示及組織
在 live555 的 BasicUsageEnvironment 模塊中,用 DelayQueueEntry 類表示一個(gè)延遲任務(wù)。該類定義如下:
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; };延遲任務(wù)通過(guò) token 來(lái)標(biāo)識(shí),token 在對(duì)象創(chuàng)建時(shí),借助于全局的 tokenCounter 產(chǎn)生。fDeltaTimeRemaining 用于表示延遲任務(wù)需要被執(zhí)行的時(shí)間距當(dāng)前時(shí)間的間隔。由 fNext 和 fPrev 不難猜到,在 BasicUsageEnvironment 模塊中是以雙向鏈表來(lái)組織延遲任務(wù)的。handleTimeout() 函數(shù)是延遲任務(wù)的主體,需要由具體的子類提供實(shí)現(xiàn)。
DelayQueueEntry 類的具體實(shí)現(xiàn)如下:
intptr_t DelayQueueEntry::tokenCounter = 0;DelayQueueEntry::DelayQueueEntry(DelayInterval delay): fDeltaTimeRemaining(delay) {fNext = fPrev = this;fToken = ++tokenCounter; }DelayQueueEntry::~DelayQueueEntry() { }void DelayQueueEntry::handleTimeout() {delete this; }BasicUsageEnvironment 模塊中實(shí)際使用 AlarmHandler 來(lái)描述延遲任務(wù)的,其定義如下:
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 類表示和組織延遲任務(wù),而在接口層,也就是 TaskScheduler 中則是通過(guò) TaskFunc 和用戶數(shù)據(jù)指針來(lái)表示延遲任務(wù)。AlarmHandler 協(xié)助完成接口的結(jié)構(gòu)到實(shí)現(xiàn)的結(jié)構(gòu)的轉(zhuǎn)換。
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; };首先來(lái)看一下 DelayQueue 類對(duì)象構(gòu)造和銷毀的過(guò)程:
DelayQueue::DelayQueue(): DelayQueueEntry(ETERNITY) {fLastSyncTime = TimeNow(); }DelayQueue::~DelayQueue() {while (fNext != this) {DelayQueueEntry* entryToRemove = fNext;removeEntry(entryToRemove);delete entryToRemove;} }然后來(lái)看一下向鏈表中添加元素的過(guò)程:
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; }通過(guò)這兩個(gè)函數(shù),可以更加清楚的看到,在 DelayQueue 中是怎么組織延遲任務(wù)的。DelayQueue 因?yàn)槠浔旧硎且粋€(gè) DelayQueueEntry,實(shí)際上它是一個(gè)環(huán)形雙向鏈表。它的 fNext 指向這個(gè)鏈表的邏輯上的頭部元素,但它本身是這個(gè)鏈表的尾部元素。雙向鏈表中每個(gè)元素的 fDeltaTimeRemaining 保存的是這個(gè)任務(wù)應(yīng)該被調(diào)度執(zhí)行的時(shí)間點(diǎn),與它前面的那個(gè)任務(wù)應(yīng)該被調(diào)度執(zhí)行的時(shí)間點(diǎn)之間的差值,當(dāng)該值為 0 時(shí),也就表示這個(gè)任務(wù)需要被執(zhí)行了。這樣也就是說(shuō), DelayQueue 是一個(gè)雙向環(huán)形的有序鏈表,順序按照所需的執(zhí)行時(shí)間排列。
removeEntry() 用于從雙向鏈表中移除一個(gè)任務(wù):
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 成立時(shí)會(huì)直接返回,也是由于 DelayQueue 實(shí)際是一個(gè)雙向環(huán)形鏈表的緣故。
DelayQueue 還提供了用于更新延遲任務(wù)執(zhí)行時(shí)間的接口:
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() 用于計(jì)算最近的一個(gè)任務(wù)執(zhí)行的時(shí)間,而 handleAlarm() 則用于執(zhí)行該任務(wù)。
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();} }延遲任務(wù)調(diào)度
看過(guò)了 live555 的 BasicUsageEnvironment 模塊中時(shí)間的表示,以及延遲任務(wù)的表示及組織之后,再來(lái)看延遲任務(wù)的調(diào)度。
BasicTaskScheduler0 類通過(guò) scheduleDelayedTask() 和 unscheduleDelayedTask() 函數(shù)實(shí)現(xiàn)定時(shí)器任務(wù)調(diào)度,它們分別用于調(diào)度一個(gè)延遲任務(wù)及取消一個(gè)延遲任務(wù),它們的實(shí)現(xiàn)如下:
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; }延遲任務(wù)調(diào)度也就是把延遲任務(wù)放進(jìn) DelayQueue 中,而取消延遲任務(wù)則是,把任務(wù)從 DelayQueue 中移除。
后面再來(lái)看延遲任務(wù)被執(zhí)行的過(guò)程。
用戶事件任務(wù)調(diào)度
用戶事件任務(wù)調(diào)度接口,讓調(diào)用者可以創(chuàng)建任務(wù),并觸發(fā)該任務(wù)在事件循環(huán)中執(zhí)行。這組接口主要包括這樣幾個(gè):createEventTrigger()、deleteEventTrigger() 和 triggerEvent(),它們分別用于創(chuàng)建任務(wù),刪除任務(wù),及觸發(fā)任務(wù)執(zhí)行。
這些接口的實(shí)現(xiàn)如下:
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 用于保存任務(wù)本身,它們分別保存任務(wù)主體函數(shù),以及執(zhí)行任務(wù)時(shí)傳入的用戶數(shù)據(jù)。它們都是數(shù)組,每個(gè)任務(wù)占用一個(gè)元素,相同索引處的元素屬于同一個(gè)任務(wù)。數(shù)組的長(zhǎng)度為 MAX_NUM_EVENT_TRIGGERS,即 32,也就是說(shuō)最多可以創(chuàng)建的任務(wù)的個(gè)數(shù)為 32。
fTriggersAwaitingHandling 用于記錄當(dāng)前觸發(fā)了哪些任務(wù)。每個(gè)任務(wù)的觸發(fā)狀態(tài)都對(duì)應(yīng)于其中的一個(gè)位,當(dāng)對(duì)應(yīng)的位置 1 時(shí),表示任務(wù)被觸發(fā),需要執(zhí)行;反之則不需要執(zhí)行。比如 fTriggeredEventHandlers 和 fTriggeredEventClientDatas 中索引 0 處的任務(wù)的觸發(fā)狀態(tài),對(duì)應(yīng)于 fTriggersAwaitingHandling 的最高位,索引 1 處的任務(wù)的觸發(fā)狀態(tài),對(duì)應(yīng)于次高位,依次類推。
創(chuàng)建任務(wù),即是在 fTriggeredEventHandlers 和 fTriggeredEventClientDatas 中為任務(wù)找到一個(gè)空閑的位置,把任務(wù)的主體函數(shù)的指針保存起來(lái),返回任務(wù)的索引在 fTriggersAwaitingHandling 中的對(duì)應(yīng)位的掩碼,作為任務(wù)的標(biāo)識(shí)。fLastUsedTriggerNum 用于防止遍歷 fTriggeredEventHandlers 查找時(shí)的無(wú)限循環(huán)。
刪除任務(wù)即是移除任務(wù)相關(guān)的所有數(shù)據(jù),包括復(fù)位 fTriggersAwaitingHandling 中的觸發(fā)狀態(tài),以及 fTriggeredEventHandlers 和 fTriggeredEventClientDatas 中任務(wù)的主體函數(shù)指針和用戶數(shù)據(jù)。
觸發(fā)事件任務(wù)則是置為任務(wù)在 fTriggersAwaitingHandling 中對(duì)應(yīng)的位,并設(shè)置任務(wù)數(shù)據(jù)。任務(wù)的實(shí)際執(zhí)行同樣需要在事件循環(huán)中執(zhí)行。
事件循環(huán)執(zhí)行框架
BasicTaskScheduler0 中執(zhí)行事件循環(huán)由 doEventLoop() 函數(shù)完成,具體實(shí)現(xiàn)如下:
void BasicTaskScheduler0::doEventLoop(char volatile* watchVariable) {// Repeatedly loop, handling readble sockets and timed events:while (1) {if (watchVariable != NULL && *watchVariable != 0) break;SingleStep();} }主要特別關(guān)注的是傳入的參數(shù) watchVariable:調(diào)用者可以通過(guò)這個(gè)參數(shù),來(lái)在事件循環(huán)的外部控制,事件循環(huán)何時(shí)結(jié)束。
Socket I/O 事件描述及其組織
BasicUsageEnvironment 模塊中,用 HandlerDescriptor 描述要監(jiān)聽(tīng)的 socket 上的事件及事件發(fā)生時(shí)的處理程序,該類定義如下:
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 為要監(jiān)聽(tīng)的 socket,conditionSet 描述要監(jiān)聽(tīng)的 socket 上的事件,handlerProc 為事件發(fā)生時(shí)的處理程序,clientData 為傳遞給事件處理程序的用戶數(shù)據(jù)。而 fNextHandler 和 fPrevHandler 則用于將
HandlerDescriptor 組織起來(lái)。不難猜到,BasicUsageEnvironment 模塊中 HandlerDescriptor 也是要被組織為雙向鏈表的。
HandlerDescriptor 類的實(shí)現(xiàn)如下:
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 來(lái)維護(hù)所有的 HandlerDescriptor,這個(gè)類的定義如下:
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 的設(shè)計(jì)與 DelayQueue/DelayQueueEntry 的設(shè)計(jì)非常相似。HandlerSet 的實(shí)現(xiàn)如下:
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 類似地,被設(shè)計(jì)為 HandlerDescriptor 的雙向循環(huán)列表,只是其中的元素的順序沒(méi)有意義。
BasicUsageEnvironment 模塊還提供了迭代器 HandlerIterator,用于遍歷HandlerSet ,其定義及實(shí)現(xiàn)如下:
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; }總結(jié)一下,可以監(jiān)聽(tīng)每個(gè) socket 上的事件,并在事件發(fā)生時(shí)執(zhí)行處理程序,監(jiān)聽(tīng)的 socket 上的事件及事件處理程序由 HandlerDescriptor 描述;所有的 HandlerDescriptor 由 HandlerSet 組織為一個(gè)雙向的循環(huán)鏈表,元素之間的實(shí)際順序沒(méi)有意義,新加入的元素被放在邏輯上的鏈表頭部。
Socket I/O 事件處理任務(wù)調(diào)度
Socket I/O 事件處理任務(wù)調(diào)度都在 BasicTaskScheduler 類中完成,這個(gè)類的定義如下:
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() 接口,分別用于描述要監(jiān)聽(tīng)其可讀事件、可寫(xiě)事件、異常事件的 socket 集合,以及要監(jiān)聽(tīng)的 socket 中 socket number 最大的那個(gè)。
Socket I/O 事件處理任務(wù)調(diào)度,由 setBackgroundHandling() 和 moveSocketHandling() 這兩個(gè)函數(shù)完成,它們的實(shí)現(xiàn)如下:
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;} }對(duì)于 setBackgroundHandling(),當(dāng) conditionSet 為非 0 值時(shí),會(huì)更新或者新建對(duì)特定 socket 的監(jiān)聽(tīng);為 0 時(shí),則將清除對(duì)該 socket 的監(jiān)聽(tīng)。 moveSocketHandling() 更新對(duì)于 socket 事件的監(jiān)聽(tīng)。
BasicTaskScheduler 的 SingleStep() 實(shí)現(xiàn)事件循環(huán)的單次迭代:
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(); }這個(gè)函數(shù)有點(diǎn)長(zhǎng),但清晰地分為如下幾個(gè)部分:
1. 根據(jù)定時(shí)器任務(wù)列表中,距當(dāng)前時(shí)間最近的任務(wù)所需執(zhí)行的時(shí)間點(diǎn)以及傳入的最大延遲時(shí)間,計(jì)算 select() 所能夠等待地最長(zhǎng)時(shí)間。
2. 執(zhí)行 select() 等待 socket 上的時(shí)間。
3. select() 超時(shí)或某個(gè) socket 上的 I/O 事件到來(lái),首先執(zhí)行發(fā)生 I/O 事件的 socket 的 I/O 事件處理程序。這個(gè)函數(shù)一次最多執(zhí)行一個(gè) socket 上的 I/O 處理程序。
4. 執(zhí)行用戶事件處理程序。也是一次最多執(zhí)行一個(gè)。
5. 執(zhí)行定時(shí)器任務(wù),同樣是一次最多執(zhí)行一個(gè)。
live555 的基礎(chǔ)設(shè)施基本上就是這些了。
live555 源碼分析系列文章
live555 源碼分析:簡(jiǎn)介
live555 源碼分析:基礎(chǔ)設(shè)施
總結(jié)
以上是生活随笔為你收集整理的live555 源码分析:基础设施的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: live555 源码分析:简介
- 下一篇: live555 源码分析:MediaSe