00001 /* 00002 * SharedQueue.cc 00003 * 00004 * Smalltalk like class library for C++ 00005 * Data queue with reader-writer synchronization. 00006 * 00007 * Copyright (c) 2005 Milan Cermak 00008 */ 00009 /* 00010 * This library is free software; you can redistribute it and/or 00011 * modify it under the terms of the GNU Lesser General Public 00012 * License as published by the Free Software Foundation; either 00013 * version 2.1 of the License, or (at your option) any later version. 00014 * 00015 * This library is distributed in the hope that it will be useful, 00016 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00017 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 00018 * Lesser General Public License for more details. 00019 * 00020 * You should have received a copy of the GNU Lesser General Public 00021 * License along with this library; if not, write to the Free Software 00022 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 00023 */ 00024 #include <stlib/os/SharedQueue.h> 00025 #include <stlib/OrderedCollection.h> 00026 #include <stlib/String.h> 00027 #include <stlib/os/Semaphore.h> 00028 00029 namespace OS { 00030 00031 SharedQueue::SharedQueue(long size) 00032 { 00033 content = new OrderedCollection(size); 00034 accessLock = Semaphore::forMutualExclusion(); 00035 emptySemaphore = new Semaphore; 00036 } 00037 00038 /* Class-accessing protocol */ 00039 String *SharedQueue::className(void) const 00040 { 00041 return new String("SharedQueue"); 00042 } 00043 00044 /* Accessing protocol */ 00045 Object *SharedQueue::next(void) 00046 { 00047 Object *data; 00048 00049 emptySemaphore->wait(); 00050 accessLock->wait(); 00051 data = content->removeFirst(); 00052 accessLock->signal(); 00053 return data; 00054 } 00055 00056 void SharedQueue::nextPut(Object *object) 00057 { 00058 accessLock->wait(); 00059 content->addLast(object); 00060 emptySemaphore->signal(); 00061 accessLock->signal(); 00062 } 00063 00064 Object *SharedQueue::peek(void) 00065 { 00066 Object *data; 00067 00068 accessLock->wait(); 00069 if (isEmpty()) data = nil; 00070 else data = content->first(); 00071 accessLock->signal(); 00072 return data; 00073 } 00074 00075 long SharedQueue::size(void) 00076 { 00077 return content->size(); 00078 } 00079 00080 /* Testing protocol */ 00081 bool SharedQueue::isEmpty(void) 00082 { 00083 return content->isEmpty(); 00084 } 00085 00086 }; /* namespace OS */