兩個線程通過一個全局buffer來交換數據,通過隊列來實現同步,其中未加入互斥量。
初步測試:MyThread產生0到無窮大的數,MyThread2打印滯後,後期還會完善。
#include <stdio.h>
#include <pthread.h>#include <stdlib.h>
//#define (unsigned int) UInt32
#define random(x) (rand()%x)
//typedef uint32_t UInt32
using namespace std;
//#define NULL 0L
class OSQueueElem
{
public:
OSQueueElem(void* buf=NULL):fBuffer(buf),fNext(NULL),fPre(NULL){}
~OSQueueElem(){}
OSQueueElem * Next(){return fNext;}
OSQueueElem * Pre(){return fPre;}
void * GetObj(){return fBuffer;}
private:
OSQueueElem * fNext;
OSQueueElem * fPre;
void * fBuffer;
friend class OSQueue;
};
class OSQueue
{
public:
OSQueue();
~OSQueue(){}
void EnQueue(OSQueueElem *elem);
OSQueueElem * DeQueue();
OSQueueElem * GetHead(){if(fLength>0)return fSentinel.fPre;return NULL;}
OSQueueElem * GetTail(){if(fLength>0)return fSentinel.fNext;return NULL;}
unsigned int GetLength(){return fLength;}
void Remove(OSQueueElem *elem){}
private:
OSQueueElem fSentinel;
unsigned int fLength;
};
OSQueue::OSQueue():fLength(0){
fSentinel.fNext=&fSentinel;
fSentinel.fPre=&fSentinel;
}
void OSQueue::EnQueue(OSQueueElem * elem){
elem->fNext=fSentinel.fNext;
elem->fPre=&fSentinel;
fSentinel.fNext->fPre=elem;
fSentinel.fNext=elem;
fLength++;
}
OSQueueElem* OSQueue::DeQueue(){
if(fLength>0){
OSQueueElem * elem=fSentinel.fPre;
fSentinel.fPre=elem->fPre;
elem->fPre->fNext=&fSentinel;
fLength--;
return elem;
}else
return NULL;
}
int buf[2];
void* MyThread(void* queue) //生產者
{
OSQueue * fQueue=(OSQueue *)queue;
while(1){
buf[0]+=1;
buf[1]=0;
printf("this is my firset thread! in data:%d\n",buf[0]);
OSQueueElem * elem = new OSQueueElem(&buf);
if(fQueue->GetLength()==0){
fQueue->EnQueue(elem);
}else{
delete elem;
}
}
}
void* MyThread2(void* queue) //消費者
{
OSQueue * fQueue=(OSQueue *)queue;
OSQueueElem * elem=NULL;
while(1){
elem=fQueue->DeQueue();
if(elem!=NULL){
void * buffer=elem->GetObj();
printf("this is my second thread! out data:%d\n",*(int*)buffer);
}
delete elem;
}
}
int main(int args,char ** argv)
{
int ret;
pthread_t tid,tid2;
printf("this is my first program ! \n");
OSQueue myQueue;
ret=pthread_create(&tid,NULL,MyThread,(void*)&myQueue);
if(ret!=0)
{
printf("pthread_create fail ! error_code:%d",ret);
}
ret=pthread_create(&tid2,NULL,MyThread2,(void*)&myQueue);
if(ret!=0)
{
printf("pthread_create 2 fail ! error_code:%d",ret);
}
pthread_exit(NULL);
return 0;
}