Question

In: Computer Science

Synchronize producer and consumer threads that use 10-item buffer for communication. Write pseudo code for both...

Synchronize producer and consumer threads that use 10-item buffer for communication. Write pseudo code for both threads. Assume that you can use void Buffer::store(Item item) and Item Buffer::get() methods, but you need to explicitly ensure that you never store more than 10 items in the buffer (to prevent overflow).

Solutions

Expert Solution

In computing, the producer-consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue.

  • The producer’s job is to generate data, put it into the buffer, and start again.
  • At the same time, the consumer is consuming the data (i.e. removing it from the buffer), one piece at a time.

Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the consumer won’t try to remove data from an empty buffer.

Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer.
An inadequate solution could result in a deadlock where both processes are waiting to be awakened.

  • LinkedList list – to store list of jobs in queue.
  • A Variable Capacity – to check for if the list is full or not
  • A mechanism to control the insertion and extraction from this list so that we do not insert into list if it is full or remove from it if it is empty.

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);

                }

            }

        }

    }

}

Important Points

  • In PC class (A class that has both produce and consume methods), a linked list of jobs and a capacity of the list is added to check that producer does not produce if the list is full.
  • In Producer class, the value is initialized as 0.
    • Also, we have an infinite outer loop to insert values in the list. Inside this loop, we have a synchronized block so that only a producer or a consumer thread runs at a time.
    • An inner loop is there before adding the jobs to list that checks if the job list is full, the producer thread gives up the intrinsic lock on PC and goes on the waiting state.
    • If the list is empty, the control passes to below the loop and it adds a value in the list.
  • In the Consumer class, we again have an infinite loop to extract a value from the list.
    • Inside, we also have an inner loop which checks if the list is empty.
    • If it is empty then we make the consumer thread give up the lock on PC and passes the control to producer thread for producing more jobs.
    • If the list is not empty, we go round the loop and removes an item from the list.
  • In both the methods, we use notify at the end of all statements. The reason is simple, once you have something in list, you can have the consumer thread consume it, or if you have consumed something, you can have the producer produce something.
  • sleep() at the end of both methods just make the output of program run in step wise manner and not display everything all at once so that you can see what actually is happening in the program.

Related Solutions

Write pseudo code for Min_Heap_Delete(A,i) which deletes the item at position i in Min_Heap A. Assume...
Write pseudo code for Min_Heap_Delete(A,i) which deletes the item at position i in Min_Heap A. Assume that A is a one-dimensional array. Hint:Think about “bubbling up” and “bubbling down” and the operations that do these, then give the best upper bound you can on the worst case running time of your method, in ordered notations.
Write PSEUDO CODE! for Min_Heap_Delete(A,i) which deletes the item at position i in Min_Heap A. Assume...
Write PSEUDO CODE! for Min_Heap_Delete(A,i) which deletes the item at position i in Min_Heap A. Assume that A is a one-dimensional array. Hint:Think about “bubbling up” and “bubbling down” and the operations that do these, then give the best upper bound you can on the worst case running time of your method, in ordered notations.
Consider the following pseudo-code: /* Global memory area accessible by threads */ #define N 100 struct...
Consider the following pseudo-code: /* Global memory area accessible by threads */ #define N 100 struct frame *emptyStack[N]; struct frame *displayQueue[N]; int main() { /* ** Initialise by allocating the memory for N frames ** And place the N frame addresses into the ** empty Stack array */ Initialise(); thread_t tid1, tid2; threadCreate(&tid1, GetFrame); threadCreate(&tid2, ShowFrame); sleep(300); } GetFrame() { struct frame *frame; struct frame local; while (1) { CameraGrab(&local); /* get a frame from the camera store it in...
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...
Counting integers greater than 10 Write the pseudo-code for a brute force approach to counting the...
Counting integers greater than 10 Write the pseudo-code for a brute force approach to counting the number of integers greater than 10 in an array of n integers. Write the pseudo-code divide-and-conquer algorithm for counting the number of integers greater than 10 in an array of n integers. Give the recurrence relation for the number of comparisons in your divide-and-conquer algorithm in part b.  
Write a pseudo code for an O (n7log3n) algorithm. Please write in C++.
Write a pseudo code for an O (n7log3n) algorithm. Please write in C++.
A customer in a grocery store is purchasing three items. Write the pseudo code that will:...
A customer in a grocery store is purchasing three items. Write the pseudo code that will: • Ask the user to enter the name of the first item purchased. Then ask the user to enter the cost of the first item purchased. Make your program user friendly. If the user says the first item purchased is milk, then ask: “What is the cost of milk.” [This should work no matter what item is entered by the user. I might buy...
Given a BST and a sum, write pseudo code to determine if the tree has a...
Given a BST and a sum, write pseudo code to determine if the tree has a root- to-leaf path such that adding up all the values along the path equals the given sum. Given the below BST and sum = 49, the array is (8, 4, 10, 1, 0, 3, 9, 15, 16). Return true, as there exist a root-to-leaf path 8− > 10− > 15− > 16 which sum is 49.
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT