Os New Program
Os New Program
Aim:
To implement a Producer-Consumer problem using multithreading in Python, where a
producer generates items and a consumer processes those items. The program will allow
the user to specify the number of items to produce and consume
Program:
import threading
import time
import queue
class ProducerConsumer:
def __init__(self, items_to_produce):
self.buffer = queue.Queue(maxsize=5)
self.items_to_produce = items_to_produce
self.producer_thread = threading.Thread(target=self.producer)
self.consumer_thread = threading.Thread(target=self.consumer)
def producer(self):
for i in range(self.items_to_produce):
item = i
self.buffer.put(item)
print(f'Produced: {item}')
time.sleep(1)
def consumer(self):
for _ in range(self.items_to_produce):
item = self.buffer.get()
squared_item = item ** 2
print(f'Consumed: {item}, Squared: {squared_item}')
time.sleep(2)
def start(self):
self.producer_thread.start()
self.consumer_thread.start()
self.producer_thread.join()
self.consumer_thread.join()
if __name__ == "__main__":
items_to_produce = int(input("Enter the number of items to produce and consume: "))
OPERATING SYSTEM LABORATORY CSE DEPARTMENT
DATE: EXP NO: PAGE NO:
pc = ProducerConsumer(items_to_produce)
pc.start()
Sample Output:
Enter the number of items to produce and consume: 5
Produced: 0
Produced: 1
Consumed: 0, Squared: 0
Produced: 2
Consumed: 1, Squared: 1
Produced: 3
Consumed: 2, Squared: 4
Produced: 4
Consumed: 3, Squared: 9
Consumed: 4, Squared: 16
Executed Output:
Enter the number of items to produce and consume: 3
Produced: 0
Produced: 1
Consumed: 0, Squared: 0
Produced: 2
Consumed: 1, Squared: 1
Consumed: 2, Squared: 4