00001 00019 #ifndef __RtcRingBuffer_h__ 00020 #define __RtcRingBuffer_h__ 00021 00022 #include <vector> 00023 #include <iostream> 00024 #include <ace/Synch.h> 00025 00026 namespace RTM { 00027 using namespace std; 00028 00053 template <class T> class RingBuffer 00054 { 00055 public: 00077 RingBuffer(int length) 00078 : m_Cond(m_Mutex), m_Oldest(0), m_Newest(length) 00079 { 00080 if (length > 1) 00081 { 00082 m_Length = length; 00083 } 00084 else 00085 { 00086 m_Length = 2; 00087 } 00088 m_Buffer.reserve(m_Length); 00089 } 00090 00114 RingBuffer(int length, T inival) 00115 : m_Cond(m_Mutex), m_Oldest(0), m_Newest(length) 00116 { 00117 if (length > 1) 00118 { 00119 m_Length = length; 00120 } 00121 else 00122 { 00123 m_Length = 2; 00124 } 00125 00126 m_Buffer.reserve(m_Length); 00127 00128 for (int i = 0; i < m_Length; i++) 00129 { 00130 m_Buffer[i] = inival; 00131 } 00132 } 00133 00153 virtual void put(const T value) 00154 { 00155 m_Buffer[m_Oldest] = value; 00156 00157 ACE_Guard<ACE_Thread_Mutex> guard(m_Mutex); 00158 m_Newest = m_Oldest; 00159 m_Oldest = (++m_Oldest) % m_Length; 00160 } 00161 00177 virtual const T& get_new() 00178 { 00179 ACE_Read_Guard<ACE_Thread_Mutex> guard(m_Mutex); 00180 00181 return m_Buffer[m_Newest]; 00182 } 00183 00199 virtual T& get_old() 00200 { 00201 ACE_Read_Guard<ACE_Thread_Mutex> guard(m_Mutex); 00202 00203 return m_Buffer[m_Oldest]; 00204 } 00205 00221 virtual T& get_back(int pos) 00222 { 00223 ACE_Read_Guard<ACE_Thread_Mutex> guard(m_Mutex); 00224 pos = pos % m_Length; 00225 00226 return m_Buffer[(m_Length + m_Newest - pos) % m_Length]; 00227 } 00228 00244 virtual T& get_front(int pos) 00245 { 00246 ACE_Read_Guard<ACE_Thread_Mutex> guard(m_Mutex); 00247 pos = pos % m_Length; 00248 00249 return m_Buffer[(m_Oldest + pos) % m_Length]; 00250 } 00251 00267 virtual int buff_length() 00268 { 00269 return m_Length; 00270 } 00271 00272 protected: 00280 ACE_Thread_Mutex m_Mutex; 00281 00289 ACE_Condition<ACE_Thread_Mutex> m_Cond; 00297 int m_Length; 00305 vector<T> m_Buffer; 00313 int m_Newest; 00321 int m_Oldest; 00322 }; 00323 00324 }; 00325 00326 00327 #endif // end of __RtcRingBuffer_h__