// queue.cpp S. Murrell 11-11-99 // This is an INTERLOCKED QUEUE of messages, suitable for communicating // between threads. It needs the threads library and the -pthread option // to CC when linking. It also needs the MESSAGE class, because those are // the things it makes a queue of. #include #include "threads.h" #include #include "message.h" class Queue { public: Queue(void): front(NULL), back(NULL) { s=create_semaphore(); } void add(Message *m); Message *remove(void); string look(void); int isempty(void); protected: Message *front, *back; semaphore s; }; void Queue::add(Message *m) { grab(s); if (back==NULL) { front=m; back=m; } else { back->next=m; back=m; } release(s); } Message *Queue::remove(void) { grab(s); if (front==NULL) { release(s); return NULL; } Message *m=front; front=front->next; if (front==NULL) back=NULL; release(s); return m; } string Queue::look(void) { grab(s); if (front==NULL) { release(s); return ""; } string r=front->msg; release(s); return r; } int Queue::isempty(void) { return (front==NULL); }