#ifndef _LIST_H_ #define _LIST_H_ #include "mutex.h" template class Iterator { public: virtual ~Iterator() {} virtual bool hasNext() const =0; virtual T* next() =0; protected: Iterator() {} Iterator(const Iterator& it); Iterator& operator=(const Iterator& it); }; template class List { public: List() {} ~List() { AutoMutex am(mutex); while(!head.isEmpty()) head.getNext()->del(); } void add(const T* part) { ListEntry* entry = new ListEntry(part); AutoMutex am(mutex); entry->add(&head, head.getNext()); } void addTail(const T* part) { ListEntry* entry = new ListEntry(part); AutoMutex am(mutex); entry->add(head.getPrev(), &head); } T* get() { AutoMutex am(mutex); ListEntry* entry = head.getNext(); T* retval = (T*)entry->getPart(); if (!head.isEmpty()) { entry->del(); delete entry; } return retval; } T* getTail() { AutoMutex am(mutex); ListEntry* entry = head.getPrev(); T* retval = (T*)entry->getPart(); if (!head.isEmpty()) { entry->del(); delete entry; } return retval; } bool isEmpty() const { AutoMutex am((Mutex&)mutex); return head.isEmpty(); } Iterator* createIterator() const { return new ListIterator(this); } protected: List(const List& l); List& operator=(const List& l); private: template class ListEntry { public: ListEntry(const TT* part = 0) : prev(this), next(this), part(part) { } void add(ListEntry* prev_, ListEntry* next_) { this->next = next_; this->prev = prev_; next_->prev = this; prev_->next = this; } void del() { next->prev = prev; prev->next = next; next = prev = this; } bool isEmpty() const { return (this->prev == this) && (this->next == this); } const TT* getPart() const { return part; } ListEntry* getPrev() const { return prev; } ListEntry* getNext() const { return next; } private: ListEntry* prev; ListEntry* next; const TT* part; }; ListEntry head; Mutex mutex; template class ListIterator : public Iterator { public: ListIterator(const List* list) : list(list) { // ((ListBase*)list)->mutex.lock(); pos = &list->head; } ~ListIterator() { // ((ListBase*)list)->mutex.unlock(); } bool hasNext() const { return (pos->getNext() != &list->head); } TT* next() { pos = pos->getNext(); return (TT*)pos->getPart(); } protected: ListIterator(const ListIterator& lit); ListIterator& operator=(const ListIterator& lit); private: const List* list; const ListEntry* pos; }; }; #endif //_LIST_H_