Question

In: Computer Science

In Java, Modify “Producer and Consumer Problem” from lecture note so that it can use all...

In Java, Modify “Producer and Consumer Problem” from lecture note so that it can use all buffer space, not “buffer_size – 1” as in the lecture note. This program should work as follows:

1. The user will run the program and will enter two numbers on the command line. Those numbers will be used for buffer size and counter limit.

2. The main program will then create two separate threads, producer and consumer thread.

3. Producer thread generates a random number through random number generator function and inserts this into buffer and prints the number. Increment counter.

4. Consumer thread goes to the buffer and takes a number in the proper order and prints it out. Increment counter.

5. After counter reaches its limit, both threads should be terminated and return to main.

6. Main program terminates.

Solutions

Expert Solution

solution:

C++ languages

having the POSIX thread(pthread) .It allows us to create multiple threads for achieving synchronisation in producer -consumer problem. It is major effective on the patform of  multiprocessor or multi-core systems where threads can be implementedat kernel level and also results in the speed of execution.

c++ has pthraed.h library which is used to create thread and perform its function.

//file name : thread.cpp
//library imported
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <random>
#include <unistd.h>
using namespace std;
//intialisation of global value;
int *buffer;
int index_value=0;
int  counter;
int count=0;
sem_t full,empty;
pthread_mutex_t mutex;
//method to create buffer of size n;
void create(int n)
{
     buffer = new int[n];
}
void intialise(int value)
{
counter=value;
}
//medthod for producer in producer consumer problem
void* produce(void* arg){
     //loop for counter
    while(1 && count<counter+1){
       //sleep declared as 1;
        sleep(1);
        //semaphore opeartion when empty
        sem_wait(&empty);
        pthread_mutex_lock(&mutex);
        //generting item value between 1 to 100
        int item = rand()%100;
        //buffer intialisation and index increment
        buffer[index_value++] = item;
        //count increases to counter while reaches counter
        count++;
        //message
        cout<<"Produced "<<item<<endl;
        pthread_mutex_unlock(&mutex);
        sem_post(&full);
    }
    return NULL;
}

void* consume(void* arg){
    while(1 && count<counter+1){
        sleep(1);
        sem_wait(&full);
        pthread_mutex_lock(&mutex);
        //decrement index and buffer indexdecrement
        int item = buffer[--index_value];
       //message
        cout<<"Consumed "<<item<<endl;
        cout<<"count :  "<<count<<"  counter : "<<counter<<endl;
        pthread_mutex_unlock(&mutex);
        sem_post(&empty);
    }
    return NULL;
    }

int main()
       {
        cout<<"Enter your Buffer size : "<<endl;
        int BUFFER_SIZE,counter_;
        cin>>BUFFER_SIZE;
        cout<<"Enter Your Counter Size : "<<endl;
        cin>>counter_;
        create(BUFFER_SIZE);
        intialise(counter_);
    pthread_t producer,consumer;
    sem_init(&empty,0,BUFFER_SIZE);
    sem_init(&full,0,0);
    pthread_mutex_init(&mutex,NULL);
    pthread_create(&producer,NULL,produce,NULL);
    pthread_create(&consumer,NULL,consume,NULL);
    pthread_exit(NULL);
    return 0;
}

Explanation :

Steps should follow to run the program

if you have g++ compiler then for compiling in the terminal type g++ thread.cpp -pthread for compiation

other wise it will give you error pthread as a undefined refrences

output :

please give me thumb up


Related Solutions

C Programming: POSIX: Producer / Consumer Modify the code below so that the Producer.c file calculates...
C Programming: POSIX: Producer / Consumer Modify the code below so that the Producer.c file calculates the Fibonacci sequence and writes the sequence to the shared-memory object. The Consumer.c file should then output the sequence. Producer.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/shm.h> #include <sys/stat.h> #include <sys/mman.h> #include <zconf.h> int main() { /* The size (in bytes) of shared-memory object */ const int SIZE = 4096; /* The name of shared-memory object */ const char *Obj =...
This is a java problem. Complete and only modify ArrayQueue.java and CircularLinkedQueue.java. Use Homework3Driver.java to test...
This is a java problem. Complete and only modify ArrayQueue.java and CircularLinkedQueue.java. Use Homework3Driver.java to test correctness of implementation of both. This package includes Homework3Driver.java, QueueInterface.java, QueueOverflowException.java, QueueUnderflowException.java, and LLNode.java Do NOT modify any of those files. The final output should be: "For ArrayQueue.java, you get 30/30 For CircularLinkedQueue.java, you get 20/20 Your final score is 50/50" This is ArrayQueue.java (the one that should be modified): public class ArrayQueue<T> implements QueueInterface<T> {    private static int CAPACITY = 100;   ...
JAVA programming language Modify the following code. Make changes so that Movies can be sorted by...
JAVA programming language Modify the following code. Make changes so that Movies can be sorted by title ----------------------------------------------------------------- package Model; import java.time.Duration; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; // TODO - Modify the movie class so that Java knows how to compare two Movies for sorting by title public class Movie extends DataStoreObj { private String title; private String description; private LocalDate releaseDate; private Duration runningTime; private Rating rating; private List<Genre> genres = new ArrayList<>(); private List<Actor> actors = new...
The bounded buffer problem is a producer-consumer problem where a producer process adds new items to...
The bounded buffer problem is a producer-consumer problem where a producer process adds new items to a shared buffer and a consumer process consumes items from that buffer (in the first-in-first-out (FIFO) order). When a producer adds a new item, the buffer size grows by one, and whenever a consumer consumes an item from the buffer, the size is reduced by one. The producer process must wait when the buffer is full likewise the consumer process must wait when the...
4. Modify the program geometryDemo to use the class basicGeometry and the threeSides code. Note from...
4. Modify the program geometryDemo to use the class basicGeometry and the threeSides code. Note from the comments in the main routine that it wants an input argument of 3 to solve for a triangle and 4 to solve for a square or rectangle. MODIFY the code to add another method in the 'threeSides' and 'fourSides' classes to return the perimeter. ASSUME the following for TRIANGLES. ** for AREA (1/2 * base * height) dimension1 is base, dimension2 is height...
Use the tree diagram technique that can be found in Lecture 12 to solve this problem....
Use the tree diagram technique that can be found in Lecture 12 to solve this problem. Suppose that 50% of all people who take a pregnancy test are, in fact, pregnant. A certain pregnancy test is known to identify 95% of pregnancies with a positive test result. However, 2% of people who are not pregnant will have a positive test result. Find the following probabilities: a. What is the probability that someone is pregnant and tests positive? b. What is...
Java Code The producer and consumer will share an integer array with a length of 5...
Java Code The producer and consumer will share an integer array with a length of 5 which is a circular buffer. The producer and consumer will also share one or two (your choice) variables to coordinate the placing and removal of items from the circular buffer. The producer process consists of a loop that writes the loop count (a value from 0 to 99) into the shared buffer. On each pass through the loop, before the producer writes into the...
Java Code The producer and consumer will share an integer array with a length of 5...
Java Code The producer and consumer will share an integer array with a length of 5 which is a circular buffer. The producer and consumer will also share one or two (your choice) variables to coordinate the placing and removal of items from the circular buffer. The producer process consists of a loop that writes the loop count (a value from 0 to 99) into the shared buffer. On each pass through the loop, before the producer writes into the...
Java Code The producer and consumer will share an integer array with a length of 5...
Java Code The producer and consumer will share an integer array with a length of 5 which is a circular buffer. The producer and consumer will also share one or two (your choice) variables to coordinate the placing and removal of items from the circular buffer. The producer process consists of a loop that writes the loop count (a value from 0 to 99) into the shared buffer. On each pass through the loop, before the producer writes into the...
Your task is to modify the program from the Java Arrays programming assignment to use text...
Your task is to modify the program from the Java Arrays programming assignment to use text files for input and output. I suggest you save acopy of the original before modifying the software. Your modified program should: contain a for loop to read the five test score into the array from a text data file. You will need to create and save a data file for the program to use. It should have one test score on each line of...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT