一个数据库连接池的简单代码

// test_pool.cpp : Defines the entry point for the console application.
//

#include <stdio.h>

//#ifndef __CONNECT_POOL_H__
//#define __CONNECT_POOL_H__

#include <queue>
#include <pthread.h>

template<class T>
class pool
{
public:
 typedef T* pointer;
 typedef T& reference;
 
public:
 static pool& instance()
 {
  static pool p;
  return p;
 }
 void init(T* ptr, int size)
 {
  for (int i = 0; i < size; i++)
   __queue.push(&ptr[i]);
 }
 
public:
 pointer get()
 {
  pthread_mutex_lock(&__queue_cs);
  while (__queue.size() <= 0)
   pthread_cond_wait(&__queue_cv, &__queue_cs);
  T* ptr = __queue.front();
  __queue.pop();
  pthread_mutex_unlock(&__queue_cs);
  return ptr;
 }
 void set(T* ptr)
 {
  pthread_mutex_lock(&__queue_cs);
  __queue.push(ptr);
  pthread_cond_signal(&__queue_cv);
  pthread_mutex_unlock(&__queue_cs);
 }
private:
 pthread_mutex_t __queue_cs;
 pthread_cond_t __queue_cv;
 std::queue<T*> __queue;
 
private:
 pool()
 {
  pthread_mutex_init(&__queue_cs, NULL);
  pthread_cond_init(&__queue_cv, NULL);
 }
};

template<class T>
class database
{
 friend class pool;
 
public:
 typedef T* pointer;
 typedef T& reference;
 
 database()
 {
  __ptr = pool<T>::instance().get();
 }
 ~database()
 {
  pool<T>::instance().set(__ptr);
 }
public:
 reference operator*() { return *__ptr; }
 pointer operator->() { return __ptr; }
private:
 T* __ptr;
};

 

class A
{public:
        int a;
};

 

int main(int argc, char** argv)
{
 A a[10];
 for (int i = 0; i < 10; i++)
  a[i].a = i;
 
 pool<A>::instance().init(a, 10);
 
 for (int j = 0; j < 10; j++)
 {
  database<A> d;
  ::printf("d.a = %d\n", d->a);
 }
 return 0;
}

 

程序只能在LINUX或UNIX下才编译

xlC main.cpp -lpthread

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值