Lunchbox  1.14.0
Multi-threaded C++ toolbox library for all application developers creating high-performance multi-threaded programs.
pool.h
1 
2 /* Copyright (c) 2010-2014, Stefan Eilemann <eile@eyescale.ch>
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_POOL_H
19 #define LUNCHBOX_POOL_H
20 
21 #include <lunchbox/scopedMutex.h> // member
22 #include <lunchbox/spinLock.h> // member
23 #include <lunchbox/thread.h> // thread-safety checks
24 
25 namespace lunchbox
26 {
28 template< typename T, bool locked = false >
29 class Pool : public boost::noncopyable
30 {
31 public:
33  Pool() : _lock( locked ? new SpinLock : 0 ) {}
34 
36  virtual ~Pool() { flush(); delete _lock; }
37 
39  T* alloc()
40  {
41  ScopedFastWrite mutex( _lock );
42  LB_TS_SCOPED( _thread );
43  if( _cache.empty( ))
44  return new T;
45 
46  T* item = _cache.back();
47  _cache.pop_back();
48  return item;
49  }
50 
52  void release( T* item )
53  {
54  ScopedFastWrite mutex( _lock );
55  LB_TS_SCOPED( _thread );
56  _cache.push_back( item );
57  }
58 
60  void flush()
61  {
62  ScopedFastWrite mutex( _lock );
63  LB_TS_SCOPED( _thread );
64  while( !_cache.empty( ))
65  {
66  delete _cache.back();
67  _cache.pop_back();
68  }
69  }
70 
71 private:
72  SpinLock* const _lock;
73  std::vector< T* > _cache;
74  LB_TS_VAR( _thread );
75 };
76 }
77 #endif // LUNCHBOX_POOL_H
T * alloc()
Definition: pool.h:39
Pool()
Construct a new pool.
Definition: pool.h:33
A fast lock for uncontended memory access.
Definition: spinLock.h:38
An object allocation pool.
Definition: pool.h:29
Abstraction layer and common utilities for multi-threaded programming.
Definition: algorithm.h:32
A scoped mutex.
Definition: scopedMutex.h:59
virtual ~Pool()
Destruct this pool.
Definition: pool.h:36
void release(T *item)
Release an item for reuse.
Definition: pool.h:52
void flush()
Delete all cached items.
Definition: pool.h:60