#include #include #include void *producer_function(void *arg); void *consumer_function(void *arg); #define BUFFERSIZE 5 int shared_buffer[BUFFERSIZE]; // shared between producer and consumer int items_in_buffer = 0; // number of items currently in buffer pthread_mutex_t shared_buffer_lock; // a lock for shared_buffer pthread_mutex_t items_in_buffer_lock; // a lock for items_in_buffer int production_done = 0; int main(void) { pthread_t producer_thread; pthread_t consumer_thread; // initialize the locks pthread_mutex_init(&shared_buffer_lock, NULL); pthread_mutex_init(&items_in_buffer_lock, NULL); { char *strbuf = (char *) malloc(9*sizeof(char)); // create the producer thread, name it "producer" strcpy(strbuf, "producer"); pthread_create(&producer_thread, NULL, &producer_function, (void *) strbuf); // create the consumer thread, name it "consumer" strcpy(strbuf, "consumer"); pthread_create(&consumer_thread, NULL, &consumer_function, (void *) strbuf); free(strbuf); } // wait for them to finish pthread_join(producer_thread, NULL); production_done = 1; pthread_join(consumer_thread, NULL); return 0; } //******************* PRODUCER LOGIC #define NUM_ITEMS_A_PRODUCER_PRODUCES 10 void *producer_function(void *arg) { int item_count = 0; printf("%s: starting\n", (char *) arg); // produce a finite number of items while (item_count < NUM_ITEMS_A_PRODUCER_PRODUCES) { while (items_in_buffer == BUFFERSIZE) { // busy wait } // grab the locks pthread_mutex_lock(&items_in_buffer_lock); pthread_mutex_lock(&shared_buffer_lock); // add the item to the shared buffer shared_buffer[items_in_buffer] = item_count++; printf("%s: produced item %d\n", (char *) arg, shared_buffer[items_in_buffer]); pthread_mutex_unlock(&shared_buffer_lock); // increment the number of items reported as in the buffer items_in_buffer++; pthread_mutex_unlock(&items_in_buffer_lock); } return NULL; } //****************** CONSUMER LOGIC void *consumer_function(void *arg) { printf(" %s: starting\n", (char *) arg); while(1) { while ((items_in_buffer == 0) && (!production_done)) { // busy wait } if (production_done) return NULL; // grab the locks pthread_mutex_lock(&shared_buffer_lock); pthread_mutex_lock(&items_in_buffer_lock); // decrement the number of items reported in the buffer items_in_buffer--; pthread_mutex_unlock(&items_in_buffer_lock); pthread_mutex_unlock(&shared_buffer_lock); printf(" %s: consumed item %d\n", (char *) arg, shared_buffer[items_in_buffer]); } }