2012-05-04 50 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. 實現消費者和生產者代碼。

真的,如果你想要更多的信息,你必須工作一點,並提出更具體的問題。祝你好運!