BufferLocked.hpp
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042 #ifndef ORO_CORELIB_BUFFER_LOCKED_HPP
00043 #define ORO_CORELIB_BUFFER_LOCKED_HPP
00044
00045 #include "os/Mutex.hpp"
00046 #include "os/MutexLock.hpp"
00047 #include "BufferInterface.hpp"
00048
00049 namespace RTT
00050 {
00051
00058 template<class T>
00059 class BufferLocked
00060 :public BufferInterface<T>
00061 {
00062 public:
00063
00064 typedef typename ReadInterface<T>::reference_t reference_t;
00065 typedef typename WriteInterface<T>::param_t param_t;
00066 typedef typename BufferInterface<T>::size_type size_type;
00067 typedef T value_t;
00068
00072 BufferLocked( size_type size, const T& initial_value = T() )
00073 : buf()
00074 {
00075 buf.resize(size, initial_value);
00076 buf.resize(0);
00077 }
00078
00082 ~BufferLocked() {}
00083
00084 bool Push( param_t item )
00085 {
00086 OS::MutexLock locker(lock);
00087 if ( buf.capacity() == buf.size() )
00088 return false;
00089 buf.push_back( item );
00090 return true;
00091 }
00092
00093 size_type Push(const std::vector<T>& items)
00094 {
00095 OS::MutexLock locker(lock);
00096 typename std::vector<T>::const_iterator itl( items.begin() );
00097 while ( buf.size() != buf.capacity() && itl != items.end() ) {
00098 buf.push_back( *itl );
00099 ++itl;
00100 }
00101 return (itl - items.begin());
00102
00103 }
00104 bool Pop( reference_t item )
00105 {
00106 OS::MutexLock locker(lock);
00107 if ( buf.empty() )
00108 return false;
00109 item = buf.front();
00110 buf.erase( buf.begin() );
00111 return true;
00112 }
00113
00114 size_type Pop(std::vector<T>& items )
00115 {
00116 OS::MutexLock locker(lock);
00117 int quant = 0;
00118 while ( !buf.empty() ) {
00119 items.push_back( buf.front() );
00120 buf.erase( buf.begin() );
00121 ++quant;
00122 }
00123 return quant;
00124 }
00125
00126 value_t front() const
00127 {
00128 OS::MutexLock locker(lock);
00129 value_t item = value_t();
00130 if ( !buf.empty() )
00131 item = buf.front();
00132 return item;
00133 }
00134
00135 size_type capacity() const {
00136 OS::MutexLock locker(lock);
00137 return buf.capacity();
00138 }
00139
00140 size_type size() const {
00141 OS::MutexLock locker(lock);
00142 return buf.size();
00143 }
00144
00145 void clear() {
00146 OS::MutexLock locker(lock);
00147 buf.clear();
00148 }
00149
00150 bool empty() const {
00151 return buf.empty();
00152 }
00153
00154 bool full() const {
00155 OS::MutexLock locker(lock);
00156 return buf.size() == buf.capacity();
00157 }
00158 private:
00159 std::vector<T> buf;
00160 mutable OS::Mutex lock;
00161
00162 };
00163 }
00164
00165 #endif // BUFFERSIMPLE_HPP