You are on page 1of 4

Punjab Engineering College,

Sector 12, Chandigarh

Assignment
OS Assignment 4b4
Ujjawal
Nalin Gupta
Kumar gupta
21103027
21103079
CSE
CSE
Q1: Make a queue of user-defined length. Generate two threads, one
would generate a random number and enqueue it. The second thread
would help in dequeuing the same and printing those values.
Code:
import threading
import queue
import random

lenOfQueue = int(input("Enter the length of the queue:\n"))


q = queue.Queue(lenOfQueue)

def enqueueNum():
while True:
if not q.full():
randomnum = random.randint(1, 100)
q.put(randomnum)

def dequeueNum():
while True:
if not q.empty():
randomnum = q.get()
print(randomnum)

enqueue_thread = threading.Thread(target=enqueueNum)
dequeue_thread = threading.Thread(target=dequeueNum)

enqueue_thread.start()
dequeue_thread.start()

Output:
Q2: 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.
Code:
import threading
import queue
import random

maxSize=int(input("Enter the Size of Buffer you want:\n"))


buffer = queue.Queue(maxsize=maxSize)
def producer():
while True:
data = random.randint(1, 100)
print("Producer produced\n", data)
buffer.put(data)

def consumer():
while True:
data = buffer.get()
print("Consumer consumed\n", data)

prodThread = threading.Thread(target=producer)
conThread = threading.Thread(target=consumer)

prodThread.start()
conThread.start()
Output

You might also like