00001 /* 00002 * Copyright (C) 2006 Helmut Grohne 00003 * 00004 * This program is free software; you can redistribute it and/or modify 00005 * it under the terms of the GNU General Public License as published by 00006 * the Free Software Foundation; either version 2 of the License, or 00007 * (at your option) any later version. 00008 * 00009 * This program is distributed in the hope that it will be useful, 00010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00012 * GNU General Public License for more details. 00013 * 00014 * You should have received a copy of the GNU General Public License 00015 * along with this program; if not, write to the Free Software 00016 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 00017 */ 00018 00019 #ifndef LIBMUTH_BLOCKINGQUEUE_H 00020 #define LIBMUTH_BLOCKINGQUEUE_H 00021 00022 #include "blockingqueue_decls.h" 00023 #include "lock.h" 00024 #include "condition.h" 00025 00026 template<class C> inline BlockingQueue<C>::BlockingQueue() : notempty(lock) { 00027 } 00028 00029 template<class C> inline bool BlockingQueue<C>::isempty() const { 00030 /* We need to lock the queue before asking it whether it is empty. */ 00031 WITHACQUIRED(this->lock); 00032 return this->queue.empty(); 00033 } 00034 00035 template<class C> inline void BlockingQueue<C>::put(const C &item) { 00036 /* The queue has to be locked for all operations. */ 00037 WITHACQUIRED(this->lock); 00038 /* Check whether the queue is empty. We only need to notify other 00039 * threads if this is the case. */ 00040 const bool wasempty(this->queue.empty()); 00041 this->queue.push(item); 00042 if(wasempty) 00043 this->notempty.notify(); 00044 } 00045 00046 template<class C> inline C BlockingQueue<C>::get() { 00047 WITHACQUIRED(this->lock); 00048 /* If the queue is empty wait. Waiting means unlocking it and locking 00049 * it when another thread has invoked .notify() and .release()d the 00050 * lock. */ 00051 while(this->queue.empty()) 00052 this->notempty.wait(); 00053 /* Get and remove the first element. */ 00054 C t(this->queue.front()); 00055 this->queue.pop(); 00056 return t; 00057 } 00058 00059 #endif