ConnPool

 //ConnObj *co = ConnPool::GetInstance()->GetConn();
 //_ConnectionPtr m_pConnection = co->conn;

 

#pragma once
#include <stdio.h>
#include <string>
#include <list>
#include <iostream>
#import "c:\Program Files\Common Files\System\ADO\msado15.dll"  no_namespace rename("EOF", "adoEOF")
#include "ConnObj.h"
using namespace std;

class ConnPool
{
private:
 static ConnPool* cpInst;
public:
 list<ConnObj*> poolList;

public:
 static ConnPool* GetInstance();
 void Init();
 ConnObj* Increase();
 ConnObj* GetConn();
 void DropConn(ConnObj* co);
public:
 ConnPool(void);
 ~ConnPool(void);
};

 

#include "StdAfx.h"
#include "ConnPool.h"
#include <algorithm>

#define MIN_COUNT 10
#define MAX_COUNT 100
HANDLE hMutex;

ConnPool::ConnPool(void)
{
 this->Init();
}

ConnPool::~ConnPool(void)
{
}

ConnPool* ConnPool::cpInst = NULL;
ConnPool* ConnPool::GetInstance()
{
 if(NULL==cpInst)
 {
  cpInst = new ConnPool();
 }
 else
 {
  return cpInst;
 }
}

void ConnPool::Init()
{
 CoInitialize(NULL);
 for(int i=0;i<MIN_COUNT;i++)
 {
  ConnObj *co = new ConnObj;

  co->OpenConn();
  if(NULL!=co)
  {
   //lock
   WaitForSingleObject(hMutex,INFINITE);
   poolList.push_back(co);
   ReleaseMutex(hMutex);
  }
 }
}

ConnObj* ConnPool::Increase()
{
 int size = poolList.size();

 if(size<MAX_COUNT)
 {
  ConnObj *co = new ConnObj;

  co->OpenConn();
  if(NULL!=co)
  {
   //lock
   WaitForSingleObject(hMutex,INFINITE);
   poolList.push_back(co);
   ReleaseMutex(hMutex);
   return co;
  }
  else
  {
   return NULL;
  }
 }
 else
 {
  return NULL;
 }
}

ConnObj* ConnPool::GetConn()
{
 bool bSuc;
 for(list<ConnObj*>::iterator it = this->poolList.begin();it!=this->poolList.end();it++)
 {
  if(!(*it)->isUsed)
  {
   WaitForSingleObject(hMutex,INFINITE);
   (*it)->isUsed = true;
   (*it)->usedCount =  (*it)->usedCount + 1;
   ReleaseMutex(hMutex);
   bSuc = true;
   return (*it);
   break;
  }
 }

 //全满
 if(!bSuc)
 {
  return Increase();
 }
}

void ConnPool::DropConn(ConnObj* co)
{
 co->isUsed = false;
 co->usedCount = co->usedCount - 1;
}

你可能感兴趣的:(OO)