-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBConnectionPool.cpp
More file actions
88 lines (71 loc) · 2.2 KB
/
DBConnectionPool.cpp
File metadata and controls
88 lines (71 loc) · 2.2 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <queue>
#include <memory>
#include <mutex>
// Mock database connection
class DBConnection {
public:
DBConnection(int id) : connId(id) {
std::cout << "DBConnection " << connId << " created.\n";
}
~DBConnection() {
std::cout << "DBConnection " << connId << " destroyed.\n";
}
void executeQuery(const std::string& query) {
std::cout << "Executing query on connection " << connId << ": " << query << "\n";
}
private:
int connId;
};
// Singleton DBConnectionPool without condition_variable
class DBConnectionPool {
public:
static const int INITIAL_CONNECTIONS = 5;
static const int MAX_CONNECTIONS = 20;
static DBConnectionPool& getInstance() {
static DBConnectionPool instance;
return instance;
}
DBConnectionPool(const DBConnectionPool&) = delete;
DBConnectionPool& operator=(const DBConnectionPool&) = delete;
std::shared_ptr<DBConnection> acquireConnection() {
std::lock_guard<std::mutex> lock(mtx);
if (!connections.empty()) {
auto conn = connections.front();
connections.pop();
return conn;
}
if (connCounter < MAX_CONNECTIONS) {
return std::make_shared<DBConnection>(++connCounter);
}
// No connection available and max reached
std::cout << "No available connections. Try again later.\n";
return nullptr;
}
void releaseConnection(std::shared_ptr<DBConnection> conn) {
std::lock_guard<std::mutex> lock(mtx);
connections.push(conn);
}
private:
DBConnectionPool() {
for (int i = 0; i < INITIAL_CONNECTIONS; i++) {
connections.push(std::make_shared<DBConnection>(++connCounter));
}
}
~DBConnectionPool() = default;
std::queue<std::shared_ptr<DBConnection>> connections;
std::mutex mtx;
int connCounter = 0;
};
// Example usage
int main() {
auto& pool = DBConnectionPool::getInstance();
for (int i = 0; i < 22; i++) {
auto conn = pool.acquireConnection();
if (conn) {
conn->executeQuery("SELECT * FROM test");
pool.releaseConnection(conn);
}
}
return 0;
}