生产者消费者使用posix

时间:2014-02-24 15:42:48

标签: c linux posix producer-consumer

我对有界缓冲区有一个标准生产者消费者问题。每当我给出不等数量的生产者或消费者时,程序不会终止。 我将插入或删除的数量限制为50 我想知道为什么会出现上述问题以及解决问题的方法

 #include<stdio.h>
 #include<pthread.h>  //Header for creating Posix Threads;
 #include<semaphore.h> 
 #include<stdlib.h>
 #define MAX 20

 typedef struct shared_buffer
  {
     int arr[20];
     int i; 
  }buffer;   

  buffer b;         //Fixed Length buffer shared memory

sem_t full,empty;    //Counting semaphores full->no of slots filled  empty ->no of slots        empty
pthread_mutex_t mutex; //mutual exclusion for critcal section
int flag=1,cnt=0;      
void * producer(void * arg)   //Producer threads method
{
  int index;   //thread Id
  index=(int)arg;

  while(flag)
   {

     sem_wait(&empty);        //will check if slot available and decrement empty count
     pthread_mutex_lock(&mutex);   //acquiring lock on process
     b.arr[b.i]=rand()%100;        //critcal section
     printf("\n Process %d Produced :%d",index,b.arr[b.i]);
     b.i++;
         cnt++;                //critcal section ends
     pthread_mutex_unlock(&mutex); //realeasing lock 
     sem_post(&full);              //increment full count 
         usleep(rand()%100);           //sleep for random time

   }
 }

 void * consumer(void * arg)
 {
  int index;
  index=(int)arg;
  while(flag)
  {   
     sem_wait(&full);                  //will check if buffer is not empty
     pthread_mutex_lock(&mutex); 
     b.i--;                           //critical section
     printf("\n Process %d consumed :%d",index,b.arr[b.i]);
     cnt++;                      //critical section ends
     pthread_mutex_unlock(&mutex);  //release lock
     sem_post(&empty);             //increment count of empty slots
     usleep(rand()%100);
  }
 }


int main(int argc,char * argv[])
{
   pthread_t Pid,Cid;
   int P,C,index,size;
   b.i=0;
 if(argc<4)
 {
    printf("Error.Usage : ./filename.out <no of producer> <no of consumer> <Buffer     Size(<=15)> \n");
   exit(0);
 }
  P=atoi(argv[1]);
  C=atoi(argv[2]);
  size=atoi(argv[3]);
  sem_init(&full,0,0);              //number of slots filled is 0
  sem_init(&empty,0,size);         //number of empty slots is buffer size
  pthread_mutex_init(&mutex,NULL);

  for (index=0;index<C;index++)     //creating C number of consumer
  {
     pthread_create(&Cid,NULL,consumer,index);
  }
  for (index=0;index<P;index++)    //creating P number of producer
  {
    pthread_create(&Pid,NULL,producer,index);
  }
while(cnt<=50)                    //maximum 50 operations allowed
   usleep(200);
   flag=0;
   printf("phew!Successful");
   pthread_exit(NULL);
   return 1;

}

2 个答案:

答案 0 :(得分:0)

以下是一些线索(未完整答案):

让我烦恼的第一件事就是你在你的循环中覆盖你的pthread_t引用。但是没关系,因为你之后不再使用它们。

第二件事是你错放了pthread_exit:应该在你创建的主题的末尾:

void * consumer_producer(void * arg)
{
    // ...
    while(flag)
    {
      // ...
    }
    pthread_exit(NULL);
}

答案 1 :(得分:0)

我猜你有竞争条件。当flag设置为0时,线程可能正在等待。其他线程可能捕获该状态并返回,因此等待线程将永远等待。

相关问题