我需要在我的项目中实现生产者-消费者问题。将创建 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;
}
最佳答案
我建议您制定一个计划并开始阅读。例如:
- 了解如何创建和管理线程。提示:pthread。
- 考虑线程将如何通信 - 通常它们使用通用数据结构。提示:消息队列
- 思考如何保护数据结构,让两个线程都可以安全地读写。提示:互斥量。
- 实现消费者和生产者代码。
真的,如果您想了解更多信息,您必须多做一些工作并提出更具体的问题。祝你好运!
关于linux - 生产者消费者实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10448353/