#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 99
#define PRODUCTION_COST 0
char producer_array[BUFFER_SIZE * 10];
char consumer_array[BUFFER_SIZE];
int producer_index = 0;
int consumer_index = 0;
pthread_mutex_t producer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t consumer_mutex = PTHREAD_MUTEX_INITIALIZER;
void *producer1(void *arg)
{
while (1)
{
pthread_mutex_lock(&producer_mutex);
if (producer_index >= BUFFER_SIZE || consumer_index >= BUFFER_SIZE)
{
pthread_mutex_unlock(&producer_mutex);
break;
}
producer_array[producer_index++] = 'G';
pthread_mutex_unlock(&producer_mutex);
}
pthread_exit(NULL);
}
void *producer2(void *arg)
{
while (1)
{
pthread_mutex_lock(&producer_mutex);
if (producer_index >= BUFFER_SIZE || consumer_index >= BUFFER_SIZE)
{
pthread_mutex_unlock(&producer_mutex);
break;
}
producer_array[producer_index++] = 'B';
pthread_mutex_unlock(&producer_mutex);
}
pthread_exit(NULL);
}
void *producer3(void *arg)
{
while (1)
{
pthread_mutex_lock(&producer_mutex);
if (producer_index >= BUFFER_SIZE || consumer_index >= BUFFER_SIZE)
{
pthread_mutex_unlock(&producer_mutex);
break;
}
producer_array[producer_index++] = 'R';
pthread_mutex_unlock(&producer_mutex);
}
pthread_exit(NULL);
}
void *consumer(void *arg)
{
while (1)
{
pthread_mutex_lock(&consumer_mutex);
if (consumer_index >= BUFFER_SIZE || producer_index >= BUFFER_SIZE)
{
pthread_mutex_unlock(&consumer_mutex);
break;
}
char last_p_char = (producer_index > 0) ? producer_array[producer_index - 1] : '\0';
if (last_p_char == 'G')
{
consumer_array[consumer_index++] = producer_array[--producer_index];
}
else if (last_p_char == 'B')
{
consumer_array[consumer_index++] = producer_array[--producer_index];
}
else if (last_p_char == 'R')
{
consumer_array[consumer_index++] = producer_array[--producer_index];
}
pthread_mutex_unlock(&consumer_mutex);
}
pthread_exit(NULL);
}
int main()
{
pthread_t producer_threads[3];
pthread_t consumer_thread;
pthread_create(&producer_threads[0], NULL, producer1, NULL);
pthread_create(&producer_threads[1], NULL, producer2, NULL);
pthread_create(&producer_threads[2], NULL, producer3, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
for (int i = 0; i < 3; i++)
{
pthread_join(producer_threads[i], NULL);
}
pthread_join(consumer_thread, NULL);
printf("Consumer Array: ");
for (int i = 0; i < consumer_index; i++)
{
printf("%c", consumer_array[i]);
}
printf("\n");
printf("Producer Array: ");
for (int i = 0; i < producer_index; i++)
{
printf("%c", producer_array[i]);
}
printf("\n");
return 0;
}