Lunchbox  1.8.0
lfQueue.h
1 
2 /* Copyright (c) 2010-2012, Stefan Eilemann <eile@equalizergraphics.com>
3  *
4  * This library is free software; you can redistribute it and/or modify it under
5  * the terms of the GNU Lesser General Public License version 2.1 as published
6  * by the Free Software Foundation.
7  *
8  * This library is distributed in the hope that it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
11  * details.
12  *
13  * You should have received a copy of the GNU Lesser General Public License
14  * along with this library; if not, write to the Free Software Foundation, Inc.,
15  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16  */
17 
18 #ifndef LUNCHBOX_LFQUEUE_H
19 #define LUNCHBOX_LFQUEUE_H
20 
21 #include <lunchbox/atomic.h> // member
22 #include <lunchbox/debug.h> // used in inline method
23 #include <lunchbox/nonCopyable.h> // base class
24 #include <lunchbox/thread.h> // thread-safety checks
25 
26 #include <vector>
27 
28 namespace lunchbox
29 {
44  template< typename T > class LFQueue : public NonCopyable
45  {
46  public:
48  LFQueue( const int32_t size )
49  : _data( size + 1 ), _readPos( 0 ), _writePos( 0 ) {}
50 
52  ~LFQueue() {}
53 
55  bool isEmpty() const { return _readPos == _writePos; }
56 
58  void clear()
59  {
60  LB_TS_SCOPED( _reader );
61  _readPos = 0;
62  _writePos = 0;
63  }
64 
71  void resize( const int32_t size )
72  {
73  LBASSERT( isEmpty( ));
74  _readPos = 0;
75  _writePos = 0;
76  _data.resize( size + 1 );
77  }
78 
87  bool pop( T& result )
88  {
89  LB_TS_SCOPED( _reader );
90  if( _readPos == _writePos )
91  return false;
92 
93  result = _data[ _readPos ];
94  _readPos = (_readPos + 1) % _data.size();
95  return true;
96  }
97 
106  bool getFront( T& result )
107  {
108  LB_TS_SCOPED( _reader );
109  if( _readPos == _writePos )
110  return false;
111 
112  result = _data[ _readPos ];
113  return true;
114  }
115 
123  bool push( const T& element )
124  {
125  LB_TS_SCOPED( _writer );
126  int32_t nextPos = (_writePos + 1) % _data.size();
127  if( nextPos == _readPos )
128  return false;
129 
130  _data[ _writePos ] = element;
131  _writePos = nextPos;
132  return true;
133  }
134 
139  size_t getCapacity() const { return _data.size() - 1; }
140 
141  private:
142  std::vector< T > _data;
143  a_int32_t _readPos;
144  a_int32_t _writePos;
145 
146  LB_TS_VAR( _reader );
147  LB_TS_VAR( _writer );
148  };
149 }
150 #endif // LUNCHBOX_LFQUEUE_H