当前位置: 动力学知识库 > 问答 > 编程问答 >

c - Consumer and Producer getting stuck

问题描述:

I'm working with 1 Producer and N Consumers where the number of consumers is taken from prompt argument.

The problem I'm facing is: My Producer thread is ending BEFORE the consumers are over. So the Producer does NOT give the sign to consumer and it's getting stuck forever...

My Code:

void* producerFunc(void* arg)

{

while(n_insertions < N_PRODUCTS)

{

sem_wait(&sem_postAvaliable);

sem_wait(&mutex);

x = produce_item();

insert_buffer(x);

sem_post(&mutex);

sem_post(&sem_posTaken);

}

pthread_exit(NULL);

}

void* consumerFunc(void* arg)

{

struct sConsumer* cons = (struct sConsumer*) arg;

while(n_consumed < N_PRODUCTS)

{

sem_wait(&sem_posTaken);//Here is where thread consumer get stuck.

//Because producer thread is finished and cant give a post in this semaphore.

sem_wait(&mutex);

remove_buffer();

sem_post(&mutex);

sem_post(&sem_postAvaliable);

}

pthread_exit(NULL);

}

int main(int argc, char const *argv[])

{

if(argc > 1)

{

int i, numConsumers = atoi(argv[1]);

pthread_t tConsumers[numConsumers], producer;

sem_init(&sem_posTaken, 0, 0);

sem_init(&sem_postAvaliable, 0, Buffer_Size);

sem_init(&mutex, 0, 1);

for(i=0; i<numConsumers; i++)

{

struct sConsumer* cons = (struct sConsumer*) malloc(sizeof(*cons));

cons->id = i;

pthread_create(&tConsumers[i], NULL, consumerFunc, (void*) cons);

}

pthread_create(&producer, NULL, producerFunc, NULL);

for(i=0; i<numConsumers; i++)

{

pthread_join(tConsumers[i], NULL);

}

pthread_join(producer, NULL);

}

else

printf("Por favor. Informe o número de consumidores\n");

return 0;

}

I tested with only 2 consumers and already found this problem. I'd like some idea/tip how may I fix it. Maybe the while loop ?

分享给朋友:
您可能感兴趣的文章:
随机阅读: