Question

In: Computer Science

make a C / C++, Java, or Python program with two processes, a producer and a...

make a C / C++, Java, or Python program with two processes, a producer and a consumer.

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 shared variable, it does a random wait of from one to five seconds (compute a new random wait value on each pass through the loop). The loop is to be executed 100 times. Each time through the loop, it places the loop count into the shared circular buffer if there is an available slot in the buffer, and updates the variable(s) used to control the use of the circular buffer (note that this will have to rap around as the array is only 5 items long). The producer must not clobber any item in the buffer that has not been read by the consumer. If the list is full, the producer must wait for the consumer to remove one or more items from the list before placing the next item in it. This wait is inside the main loop and must have a 1 second sleep in it. The buffer may get full because the producer may be faster than the consumer at times. When the producer puts its last entry into the buffer, it must add one more entry, a -1 which indicates to the consumer that it has completed.

The consumer process consists of a loop that reads from the shared circular buffer until the “I’m done” flag (the -1) is detected in the shared buffer indicating that the transfer is complete. On each pass through the loop, before it reads from the shared buffer, the consumer does a random wait of from two to five seconds (compute a new random value on each pass through the loop). It will only read a value from the shared circular buffer if there is one in the buffer it hasn’t read. If there is nothing to read, it must wait until there is something to read. When it has to wait it is to write “consumer waiting” into the output file. When waiting it should do so in a loop that has a 1 second sleep in it and write the “consumer waiting” message into the file each pass through this wait loop. The consumer must use the variable(s) it shares with the producer to determine which item in the circular buffer is the next item (remember the shared buffer is circular). After the consumer reads a value from the shared circular buffer, it writes the value into an output file and updates the variable(s) it shares with the producer (again note that this has to take into consideration the fact that this index will rap abound) to indicate that this entry is now available for use as the entry has been processed. When it completes, the consumer writes the phrase “Consumer done” into the output file. Note that the entry just before this should be 99 (the last item removed from the circular buffer). Do not write the -1 into the output buffer.

Solutions

Expert Solution

// Java program to implement solution of producer
// consumer problem.

import java.util.LinkedList;

public class Threadexample {
   public static void main(String[] args)
       throws InterruptedException
   {
       // Object of a class that has both produce()
       // and consume() methods
       final PC pc = new PC();

       // Create producer thread
       Thread t1 = new Thread(new Runnable() {
           @Override
           public void run()
           {
               try {
                   pc.produce();
               }
               catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       });

       // Create consumer thread
       Thread t2 = new Thread(new Runnable() {
           @Override
           public void run()
           {
               try {
                   pc.consume();
               }
               catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       });

       // Start both threads
       t1.start();
       t2.start();

       // t1 finishes before t2
       t1.join();
       t2.join();
   }

   // This class has a list, producer (adds items to list
   // and consumber (removes items).
   public static class PC {

       // Create a list shared by producer and consumer
       // Size of list is 2.
       LinkedList<Integer> list = new LinkedList<>();
       int capacity = 2;

       // Function called by producer thread
       public void produce() throws InterruptedException
       {
           int value = 0;
           while (true) {
               synchronized (this)
               {
                   // producer thread waits while list
                   // is full
                   while (list.size() == capacity)
                       wait();

                   System.out.println("Producer produced-"
                                   + value);

                   // to insert the jobs in the list
                   list.add(value++);

                   // notifies the consumer thread that
                   // now it can start consuming
                   notify();

                   // makes the working of program easier
                   // to understand
                   Thread.sleep(1000);
               }
           }
       }

       // Function called by consumer thread
       public void consume() throws InterruptedException
       {
           while (true) {
               synchronized (this)
               {
                   // consumer thread waits while list
                   // is empty
                   while (list.size() == 0)
                       wait();

                   // to retrive the ifrst job in the list
                   int val = list.removeFirst();

                   System.out.println("Consumer consumed-"
                                   + val);

                   // Wake up producer thread
                   notify();

                   // and sleep
                   Thread.sleep(1000);
               }
           }
       }
   }
}


Related Solutions

Write a C program to synchronize multiple producer processes and multiple consumer processes using monitor
Write a C program to synchronize multiple producer processes and multiple consumer processes using monitor
Java/Python/C++ Assignment Write a program to implement one round of AES-128 Input is the key and...
Java/Python/C++ Assignment Write a program to implement one round of AES-128 Input is the key and plaintext a. Show the plaintext as a 4x4 matrix b. Show the result after adding RoundKey0 c. Show the result after SubBytes d. Show the result after ShiftRows e. Show the result after MixColumns f. Show the result after first round
Please do this in java program. In this assignment you are required to implement the Producer...
Please do this in java program. In this assignment you are required to implement the Producer Consumer Problem . Assume that there is only one Producer and there is only one Consumer. 1. The problem you will be solving is the bounded-buffer producer-consumer problem. You are required to implement this assignment in Java This buffer can hold a fixed number of items. This buffer needs to be a first-in first-out (FIFO) buffer. You should implement this as a Circular Buffer...
In Java Please!!! 6.22 LAB: Python and sqlite basics Write a Python program that connects to...
In Java Please!!! 6.22 LAB: Python and sqlite basics Write a Python program that connects to a sqlite database. Create a table called Horses with the following fields: id (integer): a primary key and not null name (text) breed (text) height (real) birthday (text) Next, insert the following data row into the Horses table: id: 1 name: 'Babe' breed: 'Quarter Horse' height: 15.3 birthday: '2015-02-10' Output all records from the Horses table. Ex: With the above row inserted, the output...
write a program to make scientific calculator in java
Problem StatementWrite a program that uses the java Math library and implement the functionality of a scientific calculator. Your program should have the following components:1. A main menu listing all the functionality of the calculator.2. Your program should use the switch structure to switch between various options of the calculator. Your Program should also have the provision to handle invalidoption selection by the user.3. Your calculator SHOULD HAVE the following functionalities. You can add any other additional features. PLEASE MAKE...
As piece flipping to the Java Reversi program. Python program provided as an example. pdf document...
As piece flipping to the Java Reversi program. Python program provided as an example. pdf document describes one possible approach in Java. I need a solution, these are provided, Reversi.java Reversi_030_v3.py flip_list.pdf emptySquare80.gif blackPiece80.gif whitePiece80.gif
Write a Java Program using the concept of objects and classes. Make sure you have two...
Write a Java Program using the concept of objects and classes. Make sure you have two files Employee.java and EmployeeRunner.java. Use the template below for ease. (Please provide detailed explanation) Class Employee Class Variables: Name Work hour per week Hourly payment Class Methods: - Get/Sets - generateAnnualSalary(int:Duration of employment)               annual salary = Hourly payment * Work hours per week * 50 If the employee is working for more than 5 years, 10% added bonus             -void displayAnnualSalary ( )...
C programming language The program first creates a child process CP. So, there are two processes:...
C programming language The program first creates a child process CP. So, there are two processes: The parent process does the following: a. compute the summary of all the even number from 1, 2, .. 1000, and output this summary; b. wait for the termination of the child process CP, then terminate; The child process does the following: a. compute the summary of all the odd number from 1, 2, .. 1000, and output this summary; b. terminates;
In C language, Write a program called minishell that creates two child processes: one to execute...
In C language, Write a program called minishell that creates two child processes: one to execute 'ls -al' and the other to execute ‘grep minishell.c’. After the forks, the original parent process waits for both child processes to finish before it terminates. The parent should print out the pid of each child after it finishes. The standard output of 'ls -al' process should be piped to the input to the 'grep minishell.c' process. Make sure you close the unnecessary open...
Using java, I need to make a program that reverses a file. The program will read...
Using java, I need to make a program that reverses a file. The program will read the text file character by character, push the characters into a stack, then pop the characters into a new text file (with each character in revers order) EX: Hello World                       eyB       Bye            becomes    dlroW olleH I have the Stack and the Linked List part of this taken care of, I'm just having trouble connecting the stack and the text file together and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT