Back to: Operating System
0
Practical 1 (A)
Write a program to give a solution to the producer–consumer problem using shared memory.
Algorithm:
Step 1: Start
Step 2: Initialize a shared unbounded buffer and semaphore = 1.
Step 3: Decrement the semaphore to indicate that the producer has entered its critical section and to obtain mutual exclusion.
Step 4: The producer then produces the data and store it in the shared unbounded buffer.
Step 5: Increment the semaphore to indicate that the producer has exited its mutual exclusion.
Step 6: The consumer initially waits for the producer to produce some data.
Step 7: Decrement the semaphore to indicate that the consumer has entered its critical section.
Step 8: If the buffer has empty then wait for the producer.
Step 9: Consume the data from the buffer and then increment the semaphore to indicate that the consumer has exited its critical section.
Step 10: Stop
Code:
from random import randint
import random
import threading
import time
lock = threading.Lock()
shared_var = []
count = 0
def Producer():
global shared_var, count, lock
for _ in range(10):
produced_item = random.randint(0, 100)
print(f"Produced : {produced_item}")
lock.acquire()
shared_var.append(produced_item)
lock.release()
count += 1
time.sleep(random.randint(1,2))
def Consumer():
global shared_var, lock
while True:
if count == 10 and len(shared_var) == 0:
break
if not shared_var:
continue
lock.acquire()
print(f"Consumed : {shared_var.pop(0)}")
lock.release()
time.sleep(random.randint(2, 5))
print("Program started")
t1 = threading.Thread(target = Producer)
t2 = threading.Thread(target = Consumer)
t1.start()
t2.start()
t1.join()
t2.join()
print("Program Ended")
# This code is contributed by Subhashish Nabajja
Code:
from threading import Thread, Semaphore
import random
import time
full = Semaphore(0)
empty = Semaphore(10)
mutex = Semaphore(1)
class producerThread(Thread):
def __init__(self, buffer):
Thread.__init__(self)
self.buffer = buffer
def run(self):
nums = range(5)
while(True):
empty.acquire()
mutex.acquire()
num = random.randint(0, 5)
self.buffer.append(num)
print("Produced ", num)
mutex.release()
full.release()
time.sleep(1)
class consumerThread(Thread):
def __init__(self, buffer):
Thread.__init__(self)
self.buffer = buffer
def run(self):
while(True):
full.acquire()
mutex.acquire()
print("Consumed ", self.buffer.pop())
mutex.release()
empty.release()
time.sleep(1)
buffer = []
producerThread(buffer).start()
consumerThread(buffer).start()
# This code is contributed by Varaliya Mohammed