深蓝苹果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 16:12:15
/*
2中的CProdcons对象需要作为全局变量被使用,否则起不到“池”的效果,使用不方便,于是这里改为“单件”方式
*/
#include <stdio.h>#include <stdlib.h>#include <unistd.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: static CProdcons* getInstance(); void put(int data); int get(); protected: CProdcons(); ~CProdcons(); 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::getInstance(){ static CProdcons inst; return &inst;}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
调用方式如下:
void *thread_P(void *arg){ CProdcons *cp = CProdcons::getInstance(); int i = 1; while(1) cp->put(i++);} void *thread_V(void *arg){ CProdcons *cp = CProdcons::getInstance(); int i = 1; while(1) printf("%d\n",cp->get());} int main(){ int ret = 0; pthread_t thread_1; pthread_t thread_2; ret = pthread_create(&thread_1,NULL,thread_P,NULL); if(ret!=0) return -1; ret = pthread_create(&thread_2,NULL,thread_V,NULL); if(ret!=0) return -1; while(1) { sleep(10); } return 0;};
上一篇:池[2]
下一篇:Linux调试
登录 注册