PROGRAM 3
Write a program to Implement Producer
Consumer Problem solution
CLASSICAL PROBLEMS OF SYNCHRONISATION
❖ Bounded Buffer Problem
❖ Readers and Writers Problem
❖ Dining-Philosophers Problem
BOUNDED BUFFER (PRODUCER CONSUMER) PROBLEM
USING SEMAPHORE
❖ There are three entities: buffer slots, consumer and producer.
❖ Producer tries to store data in storage slots.
❖ Consumer tries to consume data from buffer storage.
❖ N buffers, each can hold one item.
❖ Initialised values:
➢ Mutex: 1
➢ Full: 0
➢ Empty: 0
STRUCTURE OF PRODUCER PROCESS
while (true) {
// produce an item
wait (empty);
wait (mutex);
// add the item to the buffer
signal (mutex);
signal (full);
}
STRUCTURE OF CONSUMER PROCESS
while (true) {
wait (full);
wait (mutex);
// remove an item from buffer
signal (mutex);
signal (empty);
// consume the removed item
}
❖ Access to the data buffer should only be by either producer or
consumer.
❖ When a producer is placing data, the consumer should not
consume.
❖ When a consumer is consuming data, the producer should not
consume.
❖ Mutex: Used to lock and release critical section (mutex=1)
❖ Empty: Keeps tab on number of empty slots in buffer.
➢ Initialized as N
❖ Full: Keeps tab on number of entities in buffer.
➢ Initialized as 0
PRODUCER
while (true) {
/* produce an item and put in nextProduced */
while (count == BUFFER_SIZE)
; // do nothing
buffer [in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
count++;
CONSUMER
while (true) {
while (count == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
/* consume the item in nextConsumed
}
PYTHON CODE IMPLEMENTATION FOR PRODUCER-
CONSUMER PROCESS
import threading
import time
CAPACITY = 10
buffer = [-1 for i in range(CAPACITY)]
in_index = 0
out_index = 0
mutex = threading.Semaphore()
empty = threading.Semaphore(CAPACITY)
full = threading.Semaphore(0)
size=int(input("Enter buffer size: "))
class Producer(threading.Thread):
def run(self):
global CAPACITY, buffer, in_index, out_index
global mutex, empty, full
items_produced = 0
counter = 0
while items_produced < size:
empty.acquire()
mutex.acquire()
counter += 1
buffer[in_index] = counter
in_index = (in_index + 1) % CAPACITY
print("Producer produced : ", counter)
mutex.release()
full.release()
time.sleep(1)
items_produced += 1
class Consumer(threading.Thread):
def run(self):
global CAPACITY, buffer, in_index, out_index, counter
global mutex, empty, full
items_consumed = 0
while items_consumed < size:
full.acquire()
mutex.acquire()
item = buffer[out_index]
out_index = (out_index + 1) % CAPACITY
print("Consumer consumed item : ", item)
mutex.release()
empty.release()
time.sleep(2.5)
items_consumed += 1
producer = Producer()
consumer = Consumer()
consumer.start()
producer.start()
producer.join()
consumer.join()
OUTPUT: