C语言 为什么我得到分割故障(核心转储)在有限的缓冲区问题?



以下代码是生产者/消费者问题的简单实现,也称为有界缓冲区问题。

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
//buffer keeps track of the number of items produced and consumed
int buffer = 0;
pthread_mutex_t lock;
// full and empty are used to keep track of the spaces empty and filled by the items
sem_t full,empty;
void *producer()
{
pthread_mutex_lock(&lock);
sem_wait(&empty);
buffer++;
printf("Producer produced %d n",buffer);
sem_post(&full);
pthread_mutex_unlock(&lock);
}
void *consumer()
{
pthread_mutex_lock(&lock);
sem_wait(&full);
printf("Consumer consumes %d n",buffer);
buffer--;
sem_post(&empty);
pthread_mutex_unlock(&lock);
}

int main()
{
pthread_t T1;
pthread_mutex_init(&lock,NULL);
sem_init(&empty,0,10);
sem_init(&full,0,0);
for(int i=0;i<10;i++)
{
pthread_create(&T1,NULL,producer(),NULL);
}
for(int i=0;i<10;i++)
{
pthread_create(&T1,NULL,consumer(),NULL);
}
pthread_join(T1,NULL);
pthread_mutex_destroy(&lock);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}

大多数时候我没有得到完整的输出,例如:消费者线程不消费所有的项目,并在分割错误卡住,生产者线程有时也不创建所有的项目。(我还固定了缓冲区的大小,不增加超过10)。有人能向我解释,为什么我一直得到分割故障在最后,并有办法解决它?

一个主要错误:

pthread_create(&T1,NULL,producer(),NULL);
…
pthread_create(&T1,NULL,consumer(),NULL);

您必须传递函数producerconsumer的(地址),而不是像您那样传递函数调用的结果。

最新更新