2012-05-04 51 views
2

我需要在我的项目中实施生产者 - 消费者问题。将创建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; 
    } 
+0

你能告诉我们的语言,限制使用(叉或线程,如何通过管道/插座/共享内存交换数据,...)等 – Huygens

+0

我将使用线程和共享内存交换数据。而且他们也会同步工作。我的意思是,当第一个生产者发布数据时,第二个数据只有在所有的调解者都得到它之后才能做到。 –

+0

我也知道这个网站不是一个乞求代码的地方,但我真的处于一个糟糕的情况。所以任何帮助对我来说都是生命的救星。非常感谢。 –

回答

2

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

  1. 阅读有关如何创建和管理线程的信息。提示:pthread。
  2. 想想如何将线程沟通 - 他们通常使用普通的数据结构。提示:消息队列
  3. 想想如何保护数据结构,从而两个线程可以读取和写入安全。提示:互斥体。
  4. 实现消费者和生产者代码。

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