项目场景:
单例模式,并能正确地析构。智能指针的使用。
connection_pool.h
/*
*File: connection_pool.h
*Author: fengwei
*/
#ifndef _CONNECTION_POOL_H
#define _CONNECTION_POOL_H
#include <mysql/jdbc.h>
#include <windows.h>
#include <list>
#include <iostream>
using namespace std;
using namespace sql;
/*通过写一个加锁的类来对共享的数据进行有效的安全控制,防止内存错误*/
class MTCMutex
{
public:
MTCMutex() :_mutex(NULL)
{
this->_mutex = CreateMutex(NULL, FALSE, NULL);
if (this->_mutex == NULL)
throw std::exception("CreateMutex 失败!");
}
virtual ~MTCMutex()
{
if (this->_mutex)
{
CloseHandle(this->_mutex);
std::cout << "mutex" << std::endl;
this->_mutex = NULL;
}
}
MTCMutex(const MTCMutex& mutex) { *this = mutex; }
MTCMutex& operator=(const MTCMutex& other)
{
if (this != &other)
{
this->_mutex = other._mutex;
}
return *this;
}
private:
HANDLE _mutex;
public:
BOOL Lock()
{
DWORD dwRet = ::WaitForSingleObject(this->_mutex, INFINITE);
if (dwRet == WAIT_OBJECT_0 || dwRet == WAIT_ABANDONED)
return TRUE;
else
return FALSE;
}
void UnLock()
{
ReleaseMutex(this->_mutex);
}
};
class ConnPool {
private:
int curSize; //当前已建立的数据库连接数量
int maxSize; //连接池中定义的最大数据库连接数
string username;
string password;
string url;
list<Connection*> connList; //连接池的容器队列 STL list 双向链表
static MTCMutex lock; //线程锁
static ConnPool *connPool;
Driver*driver;
Connection*CreateConnection(); //创建一个连接
void InitConnection(int iInitialSize); //初始化数据库连接池
void DestoryConnection(Connection *conn); //销毁数据库连接对象
void DestoryConnPool(); //销毁数据库连接池
ConnPool(string url, string user, string password, int maxSize); //构造方法
class GGarbo
{
public:
~GGarbo()
{

最低0.47元/天 解锁文章
1774

被折叠的 条评论
为什么被折叠?



