Design a concurrent program in C with a producer-consumer relationship using onl
ID: 657444 • Letter: D
Question
Design a concurrent program in C with a producer-consumer relationship using only mutex locks (no semaphores!) which allows 5 producers and 5 consumers to share 5 buffers (linked-lists) which can contain at most 8 entries. The buffers MAY NOT be globally accessible. In other words, each buffer must be defined within the threads themselves, and only shared between the appropriate producer and consumer. Take care not to allow the buffers to overflow (contain more than 8 entries) and not to allow consumers to try to consume from an empty buffer.
Explanation / Answer
typedef int item_cnt;
#define MAX_BUFFER 8
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include "buffer.h"
#define TRUE 1
pthread_mutex_t mutex;
int counter;
buffer_item buffer[MAX_BUFFER];
pthread_t tid; //Thread ID
pthread_attr_t attr; //Set of thread attributes
void *producer(void *param); /* the producer thread */
void *consumer(void *param); /* the consumer thread */
void initializeData() {
pthread_mutex_init(&mutex, NULL);
pthread_attr_init(&attr);
counter = 0;
}
/* Producer Thread */
void *producer(void *param) {
buffer_item item;
while(TRUE) {
/* generate a random number */
item = rand();
/* acquire the mutex lock */
pthread_mutex_lock(&mutex);
if(insert_item(item)) {
fprintf(stderr, " Producer report error condition ");
}
else {
printf("producer produced %d ", item);
}
/* release the mutex lock */
pthread_mutex_unlock(&mutex);
}
}
/* Consumer Thread */
void *consumer(void *param) {
buffer_item item;
while(TRUE) {
/* aquire the mutex lock */
pthread_mutex_lock(&mutex);
if(remove_item(&item)) {
fprintf(stderr, "Consumer report error condition ");
}
else {
printf("consumer consumed %d ", item);
}
/* release the mutex lock */
pthread_mutex_unlock(&mutex);
}
}
/* Add an item to the buffer */
int insert_item(buffer_item item) {
/* When the buffer is not full add the item
and increment the counter*/
if(counter < MAX_BUFFER) {
buffer[counter] = item;
counter++;
return 0;
}
else { /* Error the buffer is full */
return -1;
}
}
/* Remove an item from the buffer */
int remove_item(buffer_item *item) {
/* When the buffer is not empty remove the item
and decrement the counter */
if(counter > 0) {
*item = buffer[(counter-1)];
counter--;
return 0;
}
else { /* Error buffer empty */
return -1;
}
}
int main() {
int i;
int numProd = 5; /* Number of producer threads */
int numCons = 5; /* Number of consumer threads */
initializeData();
/* Create the producer threads */
for(i = 0; i < numProd; i++) {
pthread_create(&tid,&attr,producer,NULL);
}
/* Create the consumer threads */
for(i = 0; i < numCons; i++) {
pthread_create(&tid,&attr,consumer,NULL);
}
exit(0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.