直接上代码:
#ifndef CDATABASE_CONNECTION_POOL_H
#define CDATABASE_CONNECTION_POOL_H
#include <libpq-fe.h>
#include <windows.h> // 使用 Windows 线程库
// Initialize the database connection pool
void initConnectionPool(int poolSize, const char* conninfo);
// Get a connection from the pool
PGconn* getConnectionFromPool();
// Return a connection to the pool
void releaseConnectionToPool(PGconn* conn);
#endif // CDATABASE_CONNECTION_POOL_H
#include "CDatabaseConnectionPool.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct {
PGconn** connections;
int poolSize;
int currentSize;
CRITICAL_SECTION lock; // 使用 Windows 的临界区对象来替代 pthread_mutex_t
} ConnectionPool;
static ConnectionPool pool;
void initConnectionPool(int poolSize, const char* conninfo) {
pool.connections = (PGconn**)malloc(poolSize * sizeof(PGconn*));
if (!pool.connections) {
fprintf(stderr, "Failed to allocate memory for connection pool.\n");
return;
}
pool.poolSize = poolSize;
pool.currentSize = 0;
InitializeCriticalSection(&pool.lock); // 初始化临界区对象
for (int i = 0; i < poolSize; i++) {
PGconn* conn = PQconnectdb(conninfo);
if (PQstatus(conn) == CONNECTION_BAD) {
fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn));
PQfinish(conn);
}
else {
pool.connections[pool.currentSize++] = conn;
fprintf(stderr, "Connection %d created and added to pool.\n", i);
}
}
}
PGconn* getConnectionFromPool() {
PGconn* conn = NULL;
EnterCriticalSection(&pool.lock); // 进入临界区
if (pool.currentSize > 0) {
conn = pool.connections[--pool.currentSize];
fprintf(stderr, "Connection retrieved from pool. Remaining connections: %d\n", pool.currentSize);
}
else {
fprintf(stderr, "No connections available in pool.\n");
}