Lunchbox  1.4.0
pool.h
00001 
00002 /* Copyright (c) 2010-2012, 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 LUNCHBOX_POOL_H
00019 #define LUNCHBOX_POOL_H
00020 
00021 #include <lunchbox/nonCopyable.h>  // base class
00022 #include <lunchbox/scopedMutex.h>  // member
00023 #include <lunchbox/spinLock.h>     // member
00024 #include <lunchbox/thread.h>       // thread-safety checks
00025 
00026 namespace lunchbox
00027 {
00029     template< typename T, bool locked = false > class Pool : public NonCopyable
00030     {
00031     public:
00033         Pool() : _lock( locked ? new SpinLock : 0 ) {}
00034 
00036         virtual ~Pool() { flush(); delete _lock; }
00037 
00039         T* alloc()
00040             {
00041                 ScopedMutex< SpinLock > mutex( _lock );
00042                 LB_TS_SCOPED( _thread );
00043                 if( _cache.empty( ))
00044                     return new T;
00045 
00046                 T* item = _cache.back();
00047                 _cache.pop_back();
00048                 return item;
00049             }
00050 
00052         void release( T* item )
00053             {
00054                 ScopedMutex< SpinLock > mutex( _lock );
00055                 LB_TS_SCOPED( _thread );
00056                 _cache.push_back( item );
00057             }
00058 
00060         void flush()
00061             {
00062                 ScopedMutex< SpinLock > mutex( _lock );
00063                 LB_TS_SCOPED( _thread );
00064                 while( !_cache.empty( ))
00065                 {
00066                     delete _cache.back();
00067                     _cache.pop_back();
00068                 }
00069             }
00070 
00071     private:
00072         SpinLock* const _lock;
00073         std::vector< T* > _cache;
00074         LB_TS_VAR( _thread );
00075     };
00076 }
00077 #endif // LUNCHBOX_POOL_H