#define BUFFER_SIZE 5
-----------------------------------------------------
// consumer-producer.c
#include
#include
#include
#include
#include "buffer.h"
#define RAND_DIVISOR 100000000 //random function setup
pthread_mutex_t mutex; //setup mutex lock
sem_t full, empty; //setup binary semaphores
buffer_item buffer[BUFFER_SIZE]; //setup buffers
int counter; //setup buffer counter
pthread_t tid; //setup thread ID pthread_attr_t attr; //setup thread attributes
void *producer(void *param); //producer thread void *consumer(void *param); //consumer thread void initializeData() { //Setup locks, semaphores, and counters
pthread_mutex_init(&mutex, NULL); //setup mutex lock sem_init(&full, 0, 0); //setup full semaphore and init to 0 sem_init(&empty, 0, BUFFER_SIZE); //setup empty semaphore and init to BUFFER_SIZE pthread_attr_init(&attr); //Get default attributes counter = 0;
}
//Producer Function void *producer(void *param) { buffer_item item;
while(TRUE) { int rNum = rand() / RAND_DIVISOR; //Generate random number (Kochan) sleep(rNum); //sleep for a random interval of time
item = rand(); //random number generator sem_wait(&empty);//take empty lock pthread_mutex_lock(&mutex);//Take mutex lock
if(insert_item(item)) { fprintf(stderr, " Producer report error\n"); } else { printf("Producer Thread produced: %d\n", item); } pthread_mutex_unlock(&mutex); //release mutex lock sem_post(&full); //signal full semaphore }
}
// Consumer Function void *consumer(void *param) { buffer_item item;
while(TRUE) { int rNum = rand() / RAND_DIVISOR; //Call a random number and divide by the divisor to create a random sleep period (Kochan) sleep(rNum);
/* aquire the full lock */ sem_wait(&full); /* aquire
Cited: * * Kochan, Stephen G. Programming in C: [a Complete Introduction to the C Programming Language]. Indianapolis, IN: Sams, 2009. Print. */