C pthreads线程不执行生产者-消费者问题的函数



嗨,我正在尝试用线程和信号量实现生产者-消费者问题的解决方案。

我有两个函数,线程使用者和生产者将调用它们,但它们没有执行。我不确定我做错了什么,因为我没有得到任何错误,我的程序只是没有执行线程函数。我正在创建并加入线程,我不确定是什么原因导致问题

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdlib.h>
#include <errno.h> 
#include "buffer.h"
struct bufferStruct *item; //calls buffer structure from buffer.h
pthread_mutex_t mutex; //lock for synchronizing execution of threads(producer and consumer)
sem_t empty; //indicates buffer is empty
sem_t full;  //indicates buffer is full 
int input = 0;
int newitem;
pthread_attr_t attr;

void *producer(void *param)
{

for(int i = 0; i < 5; i++)
{
sem_wait(&empty);
pthread_mutex_lock(&mutex);
newitem = rand();
item->content[item->in] = newitem;
printf("Producer prouced item %d at position %d in buffern", newitem, item->in);
item->in = (item->in+1) % MAX_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
}
void *consumer(void * param)
{
for(int i =0; i< 5; i++)
{
sem_wait(&full);
pthread_mutex_lock(&mutex);
newitem = item->content[item->out];
printf("Consumer has consumed item %d at position %d in buffern", newitem, item->out);
item->out = (item->out+1) % MAX_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(1);
}
}

int main()
{
int initval = 1;
int initval2 = 2;
sem_init(&full, 1, 0);
sem_init(&empty, 1, MAX_SIZE);
if(pthread_mutex_init(&mutex,NULL)!=0){
printf("Mutex init failedn");
return 1;
}
pthread_attr_init(&attr);
pthread_t thread_produce, thread_consume;
printf("Starting threads...n");
pthread_create(&thread_produce, &attr, producer, (void*)&(initval));
pthread_create(&thread_consume, &attr, consumer, (void*)&(initval2));
pthread_join(thread_produce, NULL);
pthread_join(thread_consume, NULL);
printf("Threads done executing...n");
pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
exit(0);
}

您声明

struct bufferStruct *item;

则使用item而不将其分配给任何对象。未定义的行为结果。

如果我修复了这个问题(首先合成一个版本struct bufferStruct并选择一个MAX_SIZE(,那么程序编译没有错误,并且似乎成功运行了。

最新更新