Chinaunix首页 | 论坛 | 博客
  • 博客访问: 402369
  • 博文数量: 87
  • 博客积分: 2571
  • 博客等级: 少校
  • 技术积分: 920
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-29 13:10
文章分类

全部博文(87)

文章存档

2012年(49)

2011年(7)

2010年(26)

2009年(5)

分类: LINUX

2010-04-09 13:46:22

 

//文件名:CThreadPool2.cpp

//作用:  简单线程池2

//编译:  g++ CThreadPool2.cpp -o CThreadPool2 -lpthread

 

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define BUFFER_SIZE 8
#define GET_POS(x) ((x + 1) % BUFFER_SIZE)


#ifndef _CDATA_H_
#define _cDATA_H_

class CData
{
    public:
        CData(unsigned int size);
        ~CData();

        int *data;
};

CData::CData(unsigned int size)
{
    data = (int *)malloc(sizeof(unsigned int)/sizeof(char) * size);
}

CData::~CData()
{
    if(data)
        delete data;
    data = NULL;
}


#endif


#ifndef _CPRODCONS_H_
#define _CPRODCONS_H_

class CProdcons
{
    public:
        CProdcons();
        ~CProdcons();
        void put(int data);
        int get();

    private:
        CData *m_data;
        int nrRead;
        int nrWrite;
                pthread_mutex_t lock;
        pthread_cond_t notempty;
        pthread_cond_t notfull;
};

CProdcons::CProdcons()
{
    m_data = new CData(BUFFER_SIZE);
    nrRead = nrWrite = 0;
      pthread_mutex_init(&lock,NULL);
      pthread_cond_init(&notempty,NULL);
      pthread_cond_init(&notfull,NULL);
}

CProdcons::~CProdcons()
{
    if(m_data)
    {
        delete m_data;
        m_data = NULL;
    }
    pthread_mutex_destroy(&lock);
     pthread_cond_destroy(&notempty);
     pthread_cond_destroy(&notfull);    
}

void CProdcons::put(int data){

  pthread_mutex_lock(&lock);
   if( (GET_POS(nrWrite) == GET_POS(nrRead)) && (nrWrite > nrRead) )
  {
   pthread_cond_wait(&notfull, &lock) ;
  }
  m_data->data[GET_POS(nrWrite)]=data;
  nrWrite++;

  pthread_cond_signal(&notempty);
  pthread_mutex_unlock(&lock)
}

int CProdcons::get(){

  int data;
  pthread_mutex_lock(&lock);
  if( (GET_POS(nrWrite) == GET_POS(nrRead)) && (nrWrite == nrRead) )
  {
   pthread_cond_wait(&notempty, &lock);
  }
  data = m_data->data[GET_POS(nrRead)];
  nrRead++;

  pthread_cond_signal(&notfull);
  pthread_mutex_unlock(&lock);
  return data;
}

#endif

int main(int argc, char* argv[])

{

  CProdcons *cp = new CProdcons();

 

  //put/get

   cp->put(1);

   cp->put(2);

   ...

   printf("%d\n",cp->get());

 

  return 0;

}


阅读(660) | 评论(0) | 转发(0) |
0

上一篇:libevent

下一篇:池[3]

给主人留下些什么吧!~~