深蓝苹果kakablue.blog.chinaunix.net
深蓝苹果
全部博文(87)
2012年(49)
2011年(7)
2010年(26)
2009年(5)
曾德标
聆音听墨
阿4is痞
zy_chang
shanggua
点点未来
zyd_cu
咩羊。
embededg
qinjianb
yaoli041
huandala
mich_mq
redman27
风际的云
wansuiye
ynchnlui
莫不言
分类: 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(¬empty,NULL); pthread_cond_init(¬full,NULL);}CProdcons::~CProdcons(){ if(m_data) { delete m_data; m_data = NULL; } pthread_mutex_destroy(&lock); pthread_cond_destroy(¬empty); pthread_cond_destroy(¬full); }void CProdcons::put(int data){ pthread_mutex_lock(&lock); if( (GET_POS(nrWrite) == GET_POS(nrRead)) && (nrWrite > nrRead) ) { pthread_cond_wait(¬full, &lock) ; } m_data->data[GET_POS(nrWrite)]=data; nrWrite++; pthread_cond_signal(¬empty); 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(¬empty, &lock); } data = m_data->data[GET_POS(nrRead)]; nrRead++; pthread_cond_signal(¬full); 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;
}
上一篇:libevent
下一篇:池[3]
登录 注册