生产者 - 消费者实施

时间:2012-05-04 11:54:34

标签: linux unix semaphore

我需要在我的项目中实现生产者 - 消费者问题。将创建N个消费者和M个生产者。生产者将使用发布(v)调用将v数据传达给消费者。消费者将使用get_data(v)调用来获取数据副本v。我真的不知道如何实现它。请帮帮我。

我将使用C来实现它。我将为消费者创建n流程,为生产者创建流程。如果生产者发布数据,其他生产者在所有消费者获得数据之前都不能这样做。我将使用信号量和共享内存来交换数据。

我找到了类似工作的东西。但它使用线程,但我需要进程。我怎么能改变这个。

#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>

#define BUFF_SIZE 4
#define FULL 0
#define EMPTY 0
char buffer[BUFF_SIZE];
int nextIn = 0;
int nextOut = 0;

sem_t empty_sem_mutex; //producer semaphore
sem_t full_sem_mutex; //consumer semaphore

void Put(char item)
{
int value;
sem_wait(&empty_sem_mutex); //get the mutex to fill the buffer

buffer[nextIn] = item;
nextIn = (nextIn + 1) % BUFF_SIZE;
printf("Producing %c ...nextIn %d..Ascii=%d\n",item,nextIn,item);
if(nextIn==FULL)
{
  sem_post(&full_sem_mutex);
  sleep(1);
}
sem_post(&empty_sem_mutex);

}

 void * Producer()
{
  int i;
  for(i = 0; i < 10; i++)
{
  Put((char)('A'+ i % 26));
}
}

void Get()
{
int item;

sem_wait(&full_sem_mutex); // gain the mutex to consume from buffer

item = buffer[nextOut];
nextOut = (nextOut + 1) % BUFF_SIZE;
printf("\t...Consuming %c ...nextOut %d..Ascii=%d\n",item,nextOut,item);
if(nextOut==EMPTY) //its empty
{
  sleep(1);
}

sem_post(&full_sem_mutex);
}

void * Consumer()
{
int i;
for(i = 0; i < 10; i++)
{
  Get();
}
}

int main()
{
  pthread_t ptid,ctid;
  //initialize the semaphores

  sem_init(&empty_sem_mutex,0,1);
  sem_init(&full_sem_mutex,0,0);

  //creating producer and consumer threads

   if(pthread_create(&ptid, NULL,Producer, NULL))
   {
  printf("\n ERROR creating thread 1");
  exit(1);
    }

 if(pthread_create(&ctid, NULL,Consumer, NULL))
  {
  printf("\n ERROR creating thread 2");
  exit(1);
   }

 if(pthread_join(ptid, NULL)) /* wait for the producer to finish */
  {
  printf("\n ERROR joining thread");
  exit(1);
  }

  if(pthread_join(ctid, NULL)) /* wait for consumer to finish */
   {
  printf("\n ERROR joining thread");
  exit(1);
}

  sem_destroy(&empty_sem_mutex);
  sem_destroy(&full_sem_mutex);

  //exit the main thread

    pthread_exit(NULL);
  return 1;
  }

1 个答案:

答案 0 :(得分:2)

我建议你制定计划并开始阅读。例如:

  1. 了解如何创建和管理线程。提示:pthread。
  2. 考虑线程如何通信 - 通常它们使用通用数据结构。提示:消息队列
  3. 考虑如何保护数据结构,这样两个线程都可以安全地读写。提示:互斥。
  4. 实施消费者和生产者代码。
  5. 真的,如果你想了解更多信息,你必须先工作一下,然后提出更具体的问题。祝你好运!

相关问题