#include #include #define BUF_SIZE 10 #define NUM_PRODUCED 20 int buf[BUF_SIZE]; /* A buffer of limited size. */ /* At each instant, represents number of items produced but not yet consumed. */ int numItemsInBuffer = 0; /* Condition variable to signal that a slot has emptied in the buffer. */ pthread_cond_t slotAvailableCond = PTHREAD_COND_INITIALIZER; /* Condition variable to signal that a new item has been put in the buffer. */ pthread_cond_t itemAvailableCond = PTHREAD_COND_INITIALIZER; /* A mutex to control access to global variables. */ pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * producerFunction (void *arg) { int i, firstEmptySlot = 0, nextProduced; for (i=0; i= BUF_SIZE) pthread_cond_wait(&slotAvailableCond,&mutex); /* Put next produced item in the buffer. */ buf[firstEmptySlot] = nextProduced; /* Adjust variables. */ firstEmptySlot = (firstEmptySlot + 1) % BUF_SIZE; ++numItemsInBuffer; /* Notify that there is at least one item available in the buffer. */ pthread_cond_signal(&itemAvailableCond); /* Unlock the mutex. */ pthread_mutex_unlock(&mutex); } return NULL; } void * consumerFunction (void *arg) { int i, firstAvailableItem = 0, nextConsumed; for (i=0; i