Question

Solve the Consumer/Producer problem using semaphores. A skeleton program (Save it as producer_consumer.c) is provided to...

Solve the Consumer/Producer problem using semaphores. A skeleton program (Save it as producer_consumer.c) is provided to you: The main function creates 2 threads: consumer represents the consumer and executes the consume function, and producer represents the producer and executes the  produce function. You should declare and initialize 3 semaphores. Those semaphores should be used in the consume(..) and produce(...) functions.

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h> //compile and link with -pthread

#define BUFFER_SIZE 10

int buffer[BUFFER_SIZE];

int in, out;

int num;

void *produce( void *ptr ) {

int item;

while(1){

usleep(rand() % 1000); //sleep

printf("Producer wants to produce.\n");

//critical section below

item = rand() % 10;

num++;

buffer[in] = item;

in = (in + 1) % BUFFER_SIZE;

//critical section above

printf("Producer entered %d. Buffer Size = %d\n", item, num);

}

}

void *consume( void *ptr ) {

int item;

while(1){

usleep(rand() % 1000); //sleep

printf("Consumer wants to consume.\n");

//critical section below

num--;

int item = buffer[out];

out = (out + 1) % BUFFER_SIZE;

//critical section above

printf("Consumer consumed %d. Buffer Size = %d\n", item, num);

}

}

int main() {

pthread_t consumer, producer;

out = 0; //index of the item to be consumed next

in = 0; //index of the item to be produced next

num = 0; //number of items in the buffer

srand(time(NULL));

pthread_create( &consumer, NULL, consume, NULL);

pthread_create( &producer, NULL, produce, NULL);

pthread_join( producer, NULL);

pthread_join( consumer, NULL);

pthread_exit(NULL);

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//consumer producer problem solution using semaphores

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

pthread_t *producers;
pthread_t *consumers;
sem_t buf_mutex,empty_count,fill_count;
int *buf,buf_pos=-1,prod_count,con_count,buf_len;

int produce(pthread_t self)
{
int i = 0;
int p = 1 + rand()%40;

while(!pthread_equal(*(producers+i),self) && i < prod_count)
{
  i++;
}

printf("Producer %d produced %d \n",i+1,p);
return p;
}

void consume(int p,pthread_t self)
{
int i = 0;
while(!pthread_equal(*(consumers+i),self) && i < con_count)
{
  i++;
}
printf("Buffer:");
for(i=0;i<=buf_pos;++i)
{
  printf("%d ",*(buf+i));
}
printf("\nConsumer %d consumed %d \nCurrent buffer len: %d\n",i+1,p,buf_pos);
}

void* producer(void *args)
{
while(1)
{
  int p = produce(pthread_self());
  sem_wait(&empty_count);
  sem_wait(&buf_mutex);
  ++buf_pos;
  *(buf + buf_pos) = p;
  sem_post(&buf_mutex);
  sem_post(&fill_count);
  sleep(1 + rand()%3);
}
return NULL;
}

void* consumer(void *args)
{
int c;
while(1)
{
  sem_wait(&fill_count);
  sem_wait(&buf_mutex);
  c = *(buf+buf_pos);
  consume(c,pthread_self());
  --buf_pos;
  sem_post(&buf_mutex);
  sem_post(&empty_count);
  sleep(1+rand()%5);
}
return NULL;
}

int main(void)
{
int i,err;
srand(time(NULL));
sem_init(&buf_mutex,0,1);
sem_init(&fill_count,0,0);
printf("Enter the number of Producers:");
scanf("%d",&prod_count);

producers = (pthread_t*) malloc(prod_count*sizeof(pthread_t));
printf("Enter the number of Consumers:");

scanf("%d",&con_count);

consumers = (pthread_t*) malloc(con_count*sizeof(pthread_t));

printf("Enter buffer capacity:");

scanf("%d",&buf_len);

buf = (int*) malloc(buf_len*sizeof(int));
sem_init(&empty_count,0,buf_len);

for(i=0;i<prod_count;i++)
{
  err = pthread_create(producers+i,NULL,&producer,NULL);
  if(err != 0)
  {
   printf("Error creating producer %d: %s\n",i+1,strerror(err));
  }
  else
  {
   printf("Successfully created producer %d\n",i+1);
  }
}
for(i=0;i<con_count;i++)
{
  err = pthread_create(consumers+i,NULL,&consumer,NULL);
  if(err != 0)
  {
   printf("Error creating consumer %d: %s\n",i+1,strerror(err));
  }
  else
  {
   printf("Successfully created consumer %d\n",i+1);
  }
}
for(i=0;i<prod_count;i++)
{
  pthread_join(*(producers+i),NULL);
}
for(i=0;i<con_count;i++)
{
  pthread_join(*(consumers+i),NULL);
}
return 0;
}

Add a comment
Know the answer?
Add Answer to:
Solve the Consumer/Producer problem using semaphores. A skeleton program (Save it as producer_consumer.c) is provided to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer...

    In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer to the standard output. The Producer Accepts multiple consumer requests and processes each request by creating the following four threads. The reader thread will read an input file, one line at a time. It will pass each line of input to the character thread through a queue...

  • a multi-threaded producer / consumer program without any locking or signaling. It therefore has synchronization problems....

    a multi-threaded producer / consumer program without any locking or signaling. It therefore has synchronization problems. Add locks and signals so that it works correctly. /* Homework 5.X */ /* Robin Ehrlich */ /* compile: gcc Homework5.c -lpthread */ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct class {    struct class *next;    int id;    int grade; }; #define SLEEP_TIME 1 #define MAX_PRODUCE 10 static struct class *classHead = NULL; static struct class *classTail = NULL; static...

  • Producer and Consumer Code in C++ The program will contain two methods- one each for the...

    Producer and Consumer Code in C++ The program will contain two methods- one each for the producer and consumer. Both methods share access to an integer array buffer of size 50 with all values initialized to 0 at the beginning and an integer variable counter initialized to 0. As given below, the producer accesses the buffer elements and updates the element to 1 ( indicating production). The consumer changes a buffer elements to 0 (indicating consumption). Enhancements and modifications: You...

  • 9. Here are the codes for producer and consumer problems Producer: while (true) {                 /*...

    9. Here are the codes for producer and consumer problems Producer: while (true) {                 /* produce an item in next produced */                 while (counter == BUFFER_SIZE) ;                                 /* do nothing */                 buffer[in] = next_produced;                 in = (in + 1) % BUFFER_SIZE;                 counter++; } Consumer:               while (true) {                 while (counter == 0)                                 ; /* do nothing */                 next_consumed = buffer[out];                 out = (out + 1) % BUFFER_SIZE; counter--;                 /*...

  • write a C/C++ program which simulates the Producer/Consumer program in Figure 5.16 with a buffer size...

    write a C/C++ program which simulates the Producer/Consumer program in Figure 5.16 with a buffer size of one thousand. Allow the Producer to generate one million items. Use ten consumers. The program needs to perform a normal exit process after all items are consumed. Both the Producer (singular) and Consumers are to be runs as separate processes generated via fork(). The program must us Linux semaphores. The program must clean up the semaphores used and zombies created before termination. Report...

  • operating system engineering , please read the question and solve on the given skeleton code ....

    operating system engineering , please read the question and solve on the given skeleton code . Write a multi-threaded program with Semaphores as counters and pthread_mutex_t mutex to solve the producer-consumer problem: A bounded buffer is simply a global integer array of size N (2) which can be accessed by multiple threads. • Create two types of threads - Producer (2) and Consumer (2). Producers will write to the buffer, and the consumers will read the buffer. In this scenario,...

  • You are given a sample code that when edited/ improved/completed -will work as a producer consumer...

    You are given a sample code that when edited/ improved/completed -will work as a producer consumer synchronized solution. In addition to the counter, you will implement a circular linked list as a buffer of size 200 that stores data items 0 or 1. The producer and consumer take *random* turns to produce and consume- *random* numbers of elements ( turning 1 to a 0 and visa-versa-each time, as discussed in class). After each turn of the producer and/or consumer, your...

  • In C using the following 2 files to create a 3rd file that uses multiple threads...

    In C using the following 2 files to create a 3rd file that uses multiple threads to improve performance. Split the array into pieces and each piece is handled by a different thread. Use 8 threads. run and compile in linux. #include <stdio.h> #include <sys/time.h> #define BUFFER_SIZE 4000000 int countPrime=0; int numbers[BUFFER_SIZE]; int isPrime(int n) { int i; for(i=2;i<n;i++) if (n%i==0) return 0; return 1; } int main() { int i; // fill the buffer for(i=0;i<BUFFER_SIZE;i++) numbers[i] = (i+100)%100000; //...

  • so in this code, it computes the sum 1+2+....+n but i want it to compute 2*(1+2+....+n)...

    so in this code, it computes the sum 1+2+....+n but i want it to compute 2*(1+2+....+n) using semaphores implement solution to the critical section problem #include #include int sum; /* this data is shared by the thread(s) */ void *runner(void *param); /* threads call this function */ int main(int argc, char *argv[]) { pthread_t tid; /* the thread identifier */ pthread_attr_t attr; /* set of thread attributes */ if (argc != 2) { fprintf(stderr,"usage: a.out \n"); return -1; } if...

  • 1. (50 pts) Write a C or C++ program A6p1.c(pp) that accepts one command line argument which is an integer...

    1. (50 pts) Write a C or C++ program A6p1.c(pp) that accepts one command line argument which is an integer n between 2 and 6 inclusive. Generate a string of 60 random upper case English characters and store them somewhere (e.g. in a char array). Use pthread to create n threads to convert the string into a complementary string ('A'<>'Z', 'B'<->'Y', 'C''X', etc). You should divide this conversion task among the n threads as evenly as possible, Print out the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT