0
我試圖在C和線程中使用bounder緩衝來模擬生產者消費者問題。 也使用互斥和信號量。 預期的輸出是每次產品或消費時顯示緩衝區的狀態。 緩衝區大小固定爲10.最初,緩衝區項全部爲-1。當生產者生產一個項目時,該項目會替換-1。 第0項索引爲0,第1項索引爲1,依此類推.....無關緊要。 該程序詢問我們想要創建的生產者和消費者的數量。 生產工作正常....但不消耗。 線程1中出現分段錯誤。我不確定線程1是什麼。 我試圖用GDB多次調試....沒有任何希望。 //生產者消費者。Producer Consumer C中的Segementation Fault C
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
#include <unistd.h>
#define TRUE 1
int buff_size=10,i;
int buffer[25];
pthread_mutex_t mutex;
sem_t full, empty;
int counter = 0;
int consume_count=0; //No of Consumers created
int produce_count=0; //No of Producers created
void initializeData()
{
sem_init(&full, 0, 0);
sem_init(&empty, 0, buff_size);
pthread_mutex_init(&mutex, NULL);
}
int insert_item(int counter)
{
if (counter < buff_size) {
buffer[counter] = counter;
counter++;
//produce_count++;
return 0;
}
else {
printf("\n[BUFFER FULL!]");
return -1;
}
}
int remove_item()
{
printf("\n[GOING TO REMOVE AN ITEM]\n");
if (buffer[counter-1] != -1) {
buffer[counter-1] = -1;
counter--;
//consume_count++; // Commented out...
return 0;
}
else {
printf("\n[EMPTY]\n");
return -1;
}
}
void *producer(void *arg)
{
int RET = 0;
while(TRUE) {
sem_wait(&empty);
pthread_mutex_lock(&mutex);
RET = insert_item(counter);
if (RET){
printf("\nProducer Sleeping...zzZZ\n");
sleep(2);
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
if(!RET)
printf("\n[ INSERTED ]\n");
printf("\n");
for(i=0; i < buff_size ;i++)
printf("[%d] ",buffer[i]);
printf("\n");
sleep(3);
} // end of while...
}
void *consumer(void *arg)
{
int RET = 0;
while(TRUE) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
RET = remove_item(buffer);
if (RET){
printf("\nConsumer Sleeping\n");
sleep(3);
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
if(!RET) {
printf("\nConsumed\n");
printf("\n");
}
for(i=0 ; i < buff_size ; i++)
printf("%4d",buffer[i]);
printf("\n");
sleep(2);
} //end of while...
}
void main()
{
int produce, consume;
pthread_t *prod;//thread ID
pthread_t *cons;//thread ID
printf("\nEnter the no of producers: ");
scanf("%d",&produce);
printf("\nEnter the no of consumers: ");
scanf("%d",&consume);
putchar('\n');
for (i=0; i < buff_size; i++)
buffer[i] = -1;
for (i=0; i < buff_size; i++)
printf("[%d] ", buffer[i]);
printf("\n");
initializeData();
for (i = 0; i < produce; i++)
{
pthread_create(&prod[i], NULL, producer, NULL);
produce_count++;
}
for (i = 0; i < consume; i++)
{
pthread_create(&cons[i], NULL, consumer, NULL);
consume_count++;
printf("AAAAA");
}
/*for (i = 0; i < produce; i++)
pthread_join(producer, NULL);
for (i = 0; i < consume; i++)
pthread_join(consumer, NULL);*/
printf("\n===============\n[ PRODUCED: %d ]", produce_count);
printf("\n[ CONSUMED: %d ]\n==============", consume_count);
}
您正在調用gcc不正確。正確的調用是** gcc -Wall -Werror **。 –