我正在使用1 Producer
和N Consumers
,其中消费者的数量来自提示参数。
我面临的问题是:我的生产者线程在消费者结束之前就结束了。因此,制作人不会给消费者提供标志,而且它会永远陷入困境......
我的代码:
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;
}
我只测试了2个消费者并且已经发现了这个问题。我想要一些想法/提示如何解决它。也许是while循环?