2
私のプロジェクトでプロデューサー・コンシューマーの問題を実装する必要があります。 N個の消費者とM個の生産者が作られる。プロデューサはpublish(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;
}
言語、使用する制約(フォークまたはスレッド、パイプ/ソケット/共有メモリを介してデータを交換する方法など)を教えてください。 – Huygens
スレッドと共有メモリを使用してデータを交換します。また、彼らは同期して動作します。私は、最初のプロデューサーが、すべてのコンクーマーがそれを取得するまで、2番目のプロデューサーが行うことができないデータを公開するときを意味します。 –
私はこのサイトがコードを頼む場所ではないことを知っていますが、私は本当に悪いところです。だから、どんな助けでも私の命を救うことができます。どうもありがとうございます。 –