Equalizer  1.2.1
pool.h
00001 
00002 /* Copyright (c) 2010, Stefan Eilemann <eile@eyescale.ch> 
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 COBASE_POOL_H
00019 #define COBASE_POOL_H
00020 
00021 #include <co/base/nonCopyable.h>  // base class
00022 #include <co/base/scopedMutex.h>  // member
00023 #include <co/base/spinLock.h>     // member
00024 #include <co/base/thread.h>       // thread-safety checks
00025 
00026 namespace co
00027 {
00028 namespace base
00029 {
00031     template< typename T, bool locked = false > class Pool : public NonCopyable
00032     {
00033     public:
00035         Pool() : _lock( locked ? new SpinLock : 0 ) {}
00036 
00038         virtual ~Pool() { flush(); delete _lock; }
00039 
00041         T* alloc()
00042             {
00043                 ScopedMutex< SpinLock > mutex( _lock );
00044                 EQ_TS_SCOPED( _thread );
00045                 if( _cache.empty( ))
00046                     return new T;
00047 
00048                 T* item = _cache.back();
00049                 _cache.pop_back();
00050                 return item;
00051             }
00052 
00054         void release( T* item )
00055             {
00056                 ScopedMutex< SpinLock > mutex( _lock );
00057                 EQ_TS_SCOPED( _thread );
00058                 _cache.push_back( item );
00059             }
00060 
00062         void flush()
00063             {
00064                 ScopedMutex< SpinLock > mutex( _lock );
00065                 EQ_TS_SCOPED( _thread );
00066                 while( !_cache.empty( ))
00067                 {
00068                     delete _cache.back();
00069                     _cache.pop_back();
00070                 }
00071             }
00072 
00073     private:
00074         SpinLock* const _lock;
00075         std::vector< T* > _cache;
00076         EQ_TS_VAR( _thread );
00077     };
00078 }
00079 }
00080 #endif // COBASE_POOL_H
Generated on Fri Jun 8 2012 15:44:32 for Equalizer 1.2.1 by  doxygen 1.8.0