#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#define buff_sz 10
volatile int buff_idx = -1;
volatile char *buff = NULL;;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t buff_not_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t buff_not_empty = PTHREAD_COND_INITIALIZER;
void *Consumer()
{
while(1)
{
pthread_mutex_lock(&mutex);
while (buff_idx == -1)
{
pthread_cond_wait(&buff_not_empty, &mutex);
}
printf("Consumed item from:%d\t", buff_idx--);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&buff_not_full);
}
}
void *Producer()
{
while(1)
{
pthread_mutex_lock(&mutex);
while (buff_idx == buff_sz - 1)
{
pthread_cond_wait(&buff_not_full, &mutex);
}
buff[++buff_idx] = 'I';
printf("Produced item at:%d\t", buff_idx);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&buff_not_empty);
}
}
int main()
{
pthread_t producer_thread_id, consumer_thread_id;
buff = (char *) malloc(sizeof(char) * buff_sz);
pthread_create(&producer_thread_id, NULL, Producer, NULL);
pthread_create(&consumer_thread_id, NULL, Consumer, NULL);
pthread_join(producer_thread_id, NULL);
pthread_join(consumer_thread_id, NULL);
return 0;
}
Comments
Post a Comment