2015-10-11 39 views
1

我想爲單個生產者和單個消費者實現一個程序。在我的代碼下面,消費者不能消費第一件商品。我無法確定錯誤,並且這裏的項目是以同步的方式生成和使用的。我想實現它,以便生產者生成任意數量的項目,然後消費者將使用這些項目,但不是以同步方式。c中的生產者 - 消費者沒有使用信號量/條件變量

void *consumer() 
{ 
    while (1) 
    { 
     pthread_mutex_lock(&m); 

     pthread_cond_signal(&pd); 

     pthread_cond_wait(&cn, &m); 

     printf("Consumed item is : %d\n", count); 

     pthread_mutex_unlock(&m); 
     if (count == SIZE) 
     { 
     printf("Consumer can not consume.. Buffer empty..\n"); 
     break;  
     } 
    } 
} 

void *producer() 
{ 
    while (1) 
    { 
     if (count == SIZE) 
     { 
     printf("Producer can not produce.. Buffer full !!\n"); 
     break; 
     } 
     pthread_mutex_lock(&m); 
     printf("Produced item is : %d\n", ++count); 
     pthread_cond_signal(&cn); 

     if (count != SIZE) 
     pthread_cond_wait(&pd, &m); 

     pthread_mutex_unlock(&m); 

    } 
} 
+1

請修復您的縮進。 –

+0

沒有人曾經無條件等待...... – UmNyobe

+1

如果你不想讓製片人等待,那麼你爲什麼要在製片人中調用'pthread_cond_wait'?毫不意外的是,製造商會一直等到消費者發出信號。 – kaylum

回答

0

我改變了代碼來簡化它。這個簡單的方法不需要條件變量。在你的代碼中,你忘記了實際消耗,所以它不起作用。
我會用停止條件替換生產者和消費者無限循環 - 例如產生X項並停止,否則,此代碼的結果將是隨機的。生產者可以在消費者有機會運行之前填充緩衝區,或者消費者可以看到空的緩衝區並停止。

void *consumer() 
{ 
    int consumed; 
    while (1) 
    { 
     pthread_mutex_lock(&m); 
     consumed = count; 
     count = 0; // consume all 
     printf("Consumed item is : %d\n", consumed); 
     pthread_mutex_unlock(&m); 
     if (consumed == 0) 
     { 
      printf("Consumer can not consume.. Buffer empty..\n"); 
      break;  
     } 
    } 
} 

void *producer() 
{ 
    while (1) 
    { 
     pthread_mutex_lock(&m); 
     if (count == SIZE) 
     { 
      printf("Producer can not produce.. Buffer full !!\n"); 
      pthread_mutex_unlock(&m); 
      break; 
     } 
     else 
     { 
      printf("Produced item is : %d\n", ++count); 
     } 

     pthread_mutex_unlock(&m); 
    } 
} 
+0

我得到的輸出: 生產產品:1種 生產產品:2 生產的產品:3 生產項目是:4 生產項目是:5 生產者不能生產..緩衝器滿! 消費品是:5 消費者不能消費..緩衝空.. – nlm

+0

這是預期的,請閱讀我的答案。生產者填充緩衝區並存在。在生產者完成所有工作後,消費者立即清理所有5個物品。消費者第二次運行時,緩衝區當然是空的。嘗試將SIZE提升到更大的值,或者在釋放互斥體以允許其他線程運行後執行「睡眠(1)」。 – egur

相關問題