summaryrefslogtreecommitdiff
path: root/server/src/connectionpool.h
diff options
context:
space:
mode:
Diffstat (limited to 'server/src/connectionpool.h')
-rw-r--r--server/src/connectionpool.h143
1 files changed, 127 insertions, 16 deletions
diff --git a/server/src/connectionpool.h b/server/src/connectionpool.h
index 548d76a..77fc33b 100644
--- a/server/src/connectionpool.h
+++ b/server/src/connectionpool.h
@@ -33,38 +33,149 @@
#include "mutex.h"
#include "semaphore.h"
-class Database;
-
+template <class T>
class ConnectionPool {
public:
- ConnectionPool();
-
- void addDatabase(Database *db);
- void removeDatabase(Database *db);
+ void add(T t);
+ void remove(T t);
- bool testFree(Database *db);
- int numFreeDatabases();
+ bool testFree(T t);
+ int numFree();
- Database *borrowDatabase();
- void returnDatabase(Database *db);
+ T borrow();
+ void giveBack(T t);
private:
+ bool contains(std::list<T> &list, T t);
+
Semaphore semaphore;
Mutex mutex;
- std::list<Database *> activedbs;
- std::list<Database *> passivedbs;
+ std::list<T> active;
+ std::list<T> passive;
};
+template <class T>
class AutoBorrower {
public:
- AutoBorrower(ConnectionPool &pool);
+ AutoBorrower(ConnectionPool<T> &pool);
~AutoBorrower();
- Database *db();
+ T get();
private:
- ConnectionPool &pool;
- Database *_db;
+ ConnectionPool<T> &pool;
+ T t;
};
+
+//
+// Implementation is below
+//
+
+template <class T>
+void ConnectionPool<T>::add(T t)
+{
+ mutex.lock();
+ passive.push_back(t);
+ semaphore.post();
+ mutex.unlock();
+}
+
+template <class T>
+bool ConnectionPool<T>::contains(std::list<T> &list, T t)
+{
+ typename std::list<T>::iterator i = list.begin();
+ while(i != list.end()) {
+ if(*i == t) return true;
+ i++;
+ }
+
+ return false;
+}
+
+template <class T>
+void ConnectionPool<T>::remove(T t)
+{
+ mutex.lock();
+ if(contains(passive, t)) {
+ semaphore.post();
+ passive.remove(t);
+ }
+ mutex.unlock();
+}
+
+template <class T>
+bool ConnectionPool<T>::testFree(T t)
+{
+ bool testfree = false;
+
+ mutex.lock();
+ testfree = contains(passive, t);
+ mutex.unlock();
+
+ return testfree;
+}
+
+template <class T>
+int ConnectionPool<T>::numFree()
+{
+ int num;
+ mutex.lock();
+ num = passive.size();
+ mutex.unlock();
+ return num;
+}
+
+template <class T>
+T ConnectionPool<T>::borrow()
+{
+ T t = NULL;
+
+ semaphore.wait();
+
+ mutex.lock();
+
+ t = passive.front();
+ passive.remove(t);
+ active.push_back(t);
+
+ mutex.unlock();
+
+ return t;
+}
+
+template <class T>
+void ConnectionPool<T>::giveBack(T t)
+{
+ mutex.lock();
+
+ if(contains(active, t)) {
+ active.remove(t);
+ passive.push_back(t);
+ semaphore.post();
+ }
+
+ mutex.unlock();
+}
+
+
+template <class T>
+AutoBorrower<T>::AutoBorrower(ConnectionPool<T> &p)
+ : pool(p)
+{
+ t = pool.borrow();
+}
+
+template <class T>
+AutoBorrower<T>::~AutoBorrower()
+{
+ pool.giveBack(t);
+}
+
+template <class T>
+T AutoBorrower<T>::get()
+{
+ return t;
+}
+
#endif/*__PRACRO_CONNECTIONPOOL_H__*/