线程同步--生产者消费者模式

来源:互联网 发布:redux js 编辑:程序博客网 时间:2024/05/24 07:46


      两个线程通过一个全局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;
}











原创粉丝点击