Lunchbox  1.17.0
Multi-threaded C++ toolbox library for all application developers creating high-performance multi-threaded programs.
pool.h
1 
2 /* Copyright (c) 2010-2017, 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>
29 class Pool : public boost::noncopyable
30 {
31 public:
33  Pool() {}
35  virtual ~Pool() { flush(); }
37  T* alloc()
38  {
39  ScopedFastWrite mutex(_lock);
40  if (_cache.empty())
41  return new T;
42 
43  T* item = _cache.back();
44  _cache.pop_back();
45  return item;
46  }
47 
49  void release(T* item)
50  {
51  ScopedFastWrite mutex(_lock);
52  _cache.push_back(item);
53  }
54 
56  void flush()
57  {
58  ScopedFastWrite mutex(_lock);
59  while (!_cache.empty())
60  {
61  delete _cache.back();
62  _cache.pop_back();
63  }
64  }
65 
66 private:
67  SpinLock _lock;
68  std::vector<T*> _cache;
69 };
70 }
71 #endif // LUNCHBOX_POOL_H
T * alloc()
Definition: pool.h:37
A fast lock for uncontended memory access.
Definition: spinLock.h:38
A thread-safe object allocation pool.
Definition: pool.h:29
void release(T *item)
Release an item for reuse.
Definition: pool.h:49
A scoped mutex.
Definition: scopedMutex.h:82
Abstraction layer and common utilities for multi-threaded programming.
Definition: algorithm.h:29
void flush()
Delete all cached items.
Definition: pool.h:56
Pool()
Construct a new pool.
Definition: pool.h:33
virtual ~Pool()
Destruct this pool.
Definition: pool.h:35