1 #ifndef SGQUEUE_HXX_INCLUDED
2 #define SGQUEUE_HXX_INCLUDED 1
4 #include <simgear/compiler.h>
6 #if defined ( SG_HAVE_STD_INCLUDES )
13 #include "SGThread.hxx"
14 #include "SGGuard.hxx"
17 * SGQueue defines an interface for a FIFO.
18 * It can be implemented using different types of synchronization
27 * Create a new SGQueue object.
32 * Destroy this object.
37 * Returns whether this queue is empty (contains no elements).
39 * @return bool True if queue is empty, otherwisr false.
41 virtual bool empty() = 0;
44 * Add an item to the end of the queue.
46 * @param T object to add.
48 virtual void push( const T& item ) = 0;
51 * Get an item from the head of the queue.
53 * @return T next available object.
65 * A simple thread safe queue. All access functions are guarded with a mutex.
67 template<class T, class LOCK=SGMutex>
68 class SGLockedQueue : public SGQueue<T>
73 * Create a new SGLockedQueue object.
78 * Destroy this object.
83 * Returns whether this queue is empty (contains no elements).
85 * @return bool True if queue is empty, otherwisr false.
87 virtual bool empty() {
88 SGGuard<LOCK> g(mutex);
93 * Add an item to the end of the queue.
95 * @param T object to add.
97 virtual void push( const T& item ) {
98 SGGuard<LOCK> g(mutex);
103 * Get an item from the head of the queue.
105 * @return T next available object.
108 SGGuard<LOCK> g(mutex);
109 //if (fifo.empty()) throw NoSuchElementException();
110 assert( ! fifo.empty() );
114 // pthread_exit( PTHREAD_CANCELED );
116 T item = fifo.front();
123 * Mutex to serialise access.
129 SGLockedQueue(const SGLockedQueue&);
130 SGLockedQueue& operator= (const SGLockedQueue&);
134 * A guarded queue blocks threads trying to retrieve items
135 * when none are available.
138 class SGBlockingQueue : public SGQueue<T>
142 * Create a new SGBlockingQueue.
147 * Destroy this queue.
149 ~SGBlockingQueue() { mutex.unlock(); }
154 virtual bool empty() {
155 SGGuard<SGMutex> g(mutex);
160 * Add an item to the end of the queue.
162 * @param T object to add.
164 virtual void push( const T& item ) {
165 SGGuard<SGMutex> g(mutex);
171 * Get an item from the head of the queue.
172 * If no items are available then the calling thread is suspended
174 * @return T next available object.
177 SGGuard<SGMutex> g(mutex);
180 not_empty.wait(mutex);
182 assert(fifo.empty() != true);
183 //if (fifo.empty()) throw ??
185 T item = fifo.front();
193 * Mutex to serialise access.
198 * Condition to signal when queue not empty.
200 SGCondition not_empty;
204 SGBlockingQueue( const SGBlockingQueue& );
205 SGBlockingQueue& operator=( const SGBlockingQueue& );
208 #endif // SGQUEUE_HXX_INCLUDED