Welcome to mirror list, hosted at ThFree Co, Russian Federation.

object_pool.hpp « drape - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 3240ec6540c96c7edbea1aa2b1ad4a88c50d8773 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#pragma once

#include "base/assert.hpp"
#include "base/mutex.hpp"

#include "std/list.hpp"
#include "std/set.hpp"

template <typename T, typename Factory>
class ObjectPool
{
private:
#ifdef DEBUG
  set<T *> m_checkerSet;
#endif
  list<T *> m_pool;
  Factory m_factory;
  threads::Mutex m_lock;
public:
  ObjectPool(int count, Factory const & f) : m_factory(f)
  {
    for (int i = 0; i < count; ++i)
    {
      T * novice = m_factory.GetNew();
#ifdef DEBUG
      m_checkerSet.insert(novice);
#endif
      m_pool.push_back(novice);
    }
  }

  ~ObjectPool()
  {
    for (typename list<T *>::iterator it = m_pool.begin(); it != m_pool.end(); it++)
    {
      T * cur = *it;
#ifdef DEBUG
      typename set<T *>::iterator its = m_checkerSet.find(cur);
      ASSERT(its != m_checkerSet.end(), ("The same element returned twice or more!"));
      m_checkerSet.erase(its);
#endif
      delete cur;
    }
#ifdef DEBUG
    ASSERT(m_checkerSet.empty(), ("Alert! Don't all elements returned to pool!"));
#endif
  }

  T * Get()
  {
    threads::MutexGuard guard(m_lock);
    if (m_pool.empty())
    {
      T * novice = m_factory.GetNew();
#ifdef DEBUG
      m_checkerSet.insert(novice);
#endif
      return novice;
    }
    else
    {
      T * pt = m_pool.front();
      m_pool.pop_front();
      return pt;
    }
  }

  void Return(T * object)
  {
    threads::MutexGuard guard(m_lock);
    m_pool.push_back(object);
  }
};