linux - 生产者消费者实现

标签 linux unix semaphore

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

我打算用C来实现它。我将为消费者创建 n 个进程,为生产者创建 m 个进程。如果一个生产者发布一个数据,其他生产者只有在所有消费者都得到它之后才能发布。我将使用信号量和共享内存来交换数据。

我找到了类似的东西。但它正在使用线程,但我需要进程。我该如何更改它。

#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. 了解如何创建和管理线程。提示:pthread。
  2. 考虑线程将如何通信 - 通常它们使用通用数据结构。提示:消息队列
  3. 思考如何保护数据结构,让两个线程都可以安全地读写。提示:互斥量。
  4. 实现消费者和生产者代码。

真的,如果您想了解更多信息,您必须多做一些工作并提出更具体的问题。祝你好运!

关于linux - 生产者消费者实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10448353/

相关文章:

c - Sem_open导致非法寻道错误

c - 使用 "mmap"从文件读取时得到空输出

c - 通过 Bash 脚本在 C 文件中查找 "main"函数名称

unix - 如何让 Emacs 'man' 在 Tramp 上工作?

regex - 在 OSX 和 GNU 中删除带有 "find"数字的文件名

c - 线程加工

c - 一个进程写入,而另一个进程读取共享内存

java - 从命令行 Linux 运行 Java 程序

linux - 复合命令的第二行和后续行是否不受 bash 中的 HISTCONTROL 影响?

c - 如何查找底层 Linux 内核是否支持写时复制?