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 75 76 77 78 79 80 81 82 83 84 85
|
#ifndef OBJECTPOOL_H
#define OBJECTPOOL_H
#include <QHash>
#include <QHashIterator>
#include <QMutex>
#include <QWaitCondition>
template <class T>
class ObjectPool
{
public:
ObjectPool(quint32 min, quint32 max);
T* reserve();
void release(T* obj);
private:
QHash<T*, bool> pool;
QMutex mutex;
QWaitCondition waitCond;
int min;
int max;
};
template <class T>
ObjectPool<T>::ObjectPool(quint32 min, quint32 max)
: min(min), max(max)
{
Q_ASSERT(min > 0);
T* obj = nullptr;
for (int i = 0; i < min; i++)
{
obj = new T();
pool[obj] = false;
}
}
template <class T>
T* ObjectPool<T>::reserve()
{
mutex.lock();
forever
{
QHashIterator<T*, bool> i(pool);
while (i.hasNext())
{
i.next();
if (!i.value())
{
pool[i.key()] = true;
T* obj = i.key();
mutex.unlock();
return obj;
}
}
// Check if we can enlarge the pool
if (pool.size() < max)
{
T* obj = new T();
pool[i.key()] = true;
mutex.unlock();
return obj;
}
// Wait for release
waitCond.wait(&mutex);
}
// no need to unlock, because the loop will repeat
// until the free obj is found and then mutex is unlocked.
}
template <class T>
void ObjectPool<T>::release(T* obj)
{
mutex.lock();
pool[obj] = false;
mutex.unlock();
waitCond.wakeOne();
}
#endif // OBJECTPOOL_H
|