Lunchbox
1.6.0
|
00001 00002 /* Copyright (c) 2010-2012, Stefan Eilemann <eile@equalizergraphics.com> 00003 * 00004 * This library is free software; you can redistribute it and/or modify it under 00005 * the terms of the GNU Lesser General Public License version 2.1 as published 00006 * by the Free Software Foundation. 00007 * 00008 * This library is distributed in the hope that it will be useful, but WITHOUT 00009 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 00010 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more 00011 * details. 00012 * 00013 * You should have received a copy of the GNU Lesser General Public License 00014 * along with this library; if not, write to the Free Software Foundation, Inc., 00015 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 00016 */ 00017 00018 #ifndef LUNCHBOX_LFQUEUE_H 00019 #define LUNCHBOX_LFQUEUE_H 00020 00021 #include <lunchbox/atomic.h> // member 00022 #include <lunchbox/debug.h> // used in inline method 00023 #include <lunchbox/nonCopyable.h> // base class 00024 #include <lunchbox/thread.h> // thread-safety checks 00025 00026 #include <vector> 00027 00028 namespace lunchbox 00029 { 00044 template< typename T > class LFQueue : public NonCopyable 00045 { 00046 public: 00048 LFQueue( const int32_t size ) 00049 : _data( size + 1 ), _readPos( 0 ), _writePos( 0 ) {} 00050 00052 ~LFQueue() {} 00053 00055 bool isEmpty() const { return _readPos == _writePos; } 00056 00058 void clear() 00059 { 00060 LB_TS_SCOPED( _reader ); 00061 _readPos = 0; 00062 _writePos = 0; 00063 } 00064 00071 void resize( const int32_t size ) 00072 { 00073 LBASSERT( isEmpty( )); 00074 _readPos = 0; 00075 _writePos = 0; 00076 _data.resize( size + 1 ); 00077 } 00078 00087 bool pop( T& result ) 00088 { 00089 LB_TS_SCOPED( _reader ); 00090 if( _readPos == _writePos ) 00091 return false; 00092 00093 result = _data[ _readPos ]; 00094 _readPos = (_readPos + 1) % _data.size(); 00095 return true; 00096 } 00097 00106 bool getFront( T& result ) 00107 { 00108 LB_TS_SCOPED( _reader ); 00109 if( _readPos == _writePos ) 00110 return false; 00111 00112 result = _data[ _readPos ]; 00113 return true; 00114 } 00115 00123 bool push( const T& element ) 00124 { 00125 LB_TS_SCOPED( _writer ); 00126 int32_t nextPos = (_writePos + 1) % _data.size(); 00127 if( nextPos == _readPos ) 00128 return false; 00129 00130 _data[ _writePos ] = element; 00131 _writePos = nextPos; 00132 return true; 00133 } 00134 00139 size_t getCapacity() const { return _data.size() - 1; } 00140 00141 private: 00142 std::vector< T > _data; 00143 a_int32_t _readPos; 00144 a_int32_t _writePos; 00145 00146 LB_TS_VAR( _reader ); 00147 LB_TS_VAR( _writer ); 00148 }; 00149 } 00150 #endif // LUNCHBOX_LFQUEUE_H