forked from moulo1982/MyWarehouse
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDBConnectPool.cpp
More file actions
65 lines (53 loc) · 1.75 KB
/
DBConnectPool.cpp
File metadata and controls
65 lines (53 loc) · 1.75 KB
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
#include "DBConnectPool.h"
const char* keys[] = { "host", "port", "dbname", "user", "password", "connect_timeout", NULL };
//const char* values[] = { "120.132.85.254", "5432", "postgres", "postgres", "Gonzo1982", "10", NULL };
const char* values[] = { "127.0.0.1", "5432", "postgres", "postgres", "Gonzo1982", "10", NULL };
static void
exit_nicely(PGconn *conn)
{
PQfinish(conn);
exit(1);
}
DBConnectPool::DBConnectPool(boost::circular_buffer<PGconn*>::capacity_type n) : m_connPool(n)
{
LOG("Begin DBConnectPool(%d)... \n", n);
for (size_t i = 1; i <= n; i++)
{
PGconn *conn = PQconnectdbParams(keys, values, 0);
ConnStatusType s = PQstatus(conn);
if (s != CONNECTION_OK)
{
LOG("Connection to database failed: code:%d, msg:%s \n",
s, PQerrorMessage(conn));
exit_nicely(conn);
}
m_connPool.push_back(conn);
}
}
std::shared_ptr<PGconn> DBConnectPool::getConn()
{
std::shared_ptr<PGconn> conn;
std::unique_lock<std::mutex> lk(m_lock);
m_empty_cv.wait(lk, [this]{return !m_connPool.empty(); });
std::weak_ptr<DBConnectPool> wp(shared_from_this());
conn.reset(m_connPool.front(), [wp](PGconn *conn)
{
std::shared_ptr<DBConnectPool> sp(wp.lock());
if (sp)
sp->releaseConn(conn);
else
PQfinish(conn);
});
m_connPool.pop_front();
m_full_cv.notify_one();
LOG("Begin getConn... conn=%x\n", conn.get());
return conn;
}
void DBConnectPool::releaseConn(PGconn *conn)
{
LOG("Begin releaseConn... conn=%x\n", conn);
std::unique_lock<std::mutex> lk(m_lock);
m_full_cv.wait(lk, [this]{return !m_connPool.full(); });
m_connPool.push_back(conn);
m_empty_cv.notify_one();
}