POSIX Thread. Почему прекращается работа программы производителя-потребителя?
Я попробовал написать простую программу производитель-потребитель на языке C, с использованием POSIX Thread — библиотеки для работы с потоками.
В коде есть глобальная очередь, откуда потоки обмениваются информацией. Очередь тестирована и корректно должна работать. Также участвуют два потока:
- Производитель. Генерирует случайное число и помещает его в очередь;
- Потребитель. Извлекает число из очереди и печатает его на экран.
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include "queue.h"
pthread_mutex_t mutex;
pthread_cond_t pcond;
pthread_cond_t ccond;
static const unsigned int X = 10;
void* producer(void* args)
{
for (int i = 0; i < X; i++)
{
pthread_mutex_lock(&mutex);
while (queue_is_full())
pthread_cond_wait(&pcond, &mutex);
if (queue_is_empty())
pthread_cond_signal(&ccond);
queue_enqueue(rand() % (9999 + 1 - 0) + 0);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void* consumer(void* args)
{
for (int i = 0; i < X; i++)
{
pthread_mutex_lock(&mutex);
while (queue_is_empty())
pthread_cond_wait(&ccond, &mutex);
if (queue_is_full())
pthread_cond_signal(&pcond);
printf("%i", queue_dequeue());
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(void)
{
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&pcond, NULL);
pthread_cond_init(&ccond, NULL);
pthread_t thProducer, thConsumer;
pthread_create(&thProducer, NULL, producer, NULL);
pthread_create(&thConsumer, NULL, consumer, NULL);
pthread_join(thProducer, NULL);
pthread_join(thConsumer, NULL);
return 0;
}
Эта программа при запуске прекращает свою работу. Соответствующее сообщение приходит от системы сразу же после запуска программы. Как мне исправить программу?