Untitled
unknown
plain_text
2 years ago
2.4 kB
8
Indexable
import threading
import random
import time
ARRAY_SIZE = 10
NUM_PRODUCERS = 3
NUM_CONSUMERS = 3
TOTAL_PRODUCTIONS = 10000
shared_array = [None] * ARRAY_SIZE
producers_activity_file = open("Producers_activity.txt", "w")
consumers_activity_file = open("Consumers_activity.txt", "w")
mutex = threading.Semaphore(1)
full_sem = threading.Semaphore(0)
empty_sem = threading.Semaphore(ARRAY_SIZE)
# 1.a
def producer(producer_id):
for production_number in range(1, TOTAL_PRODUCTIONS + 1):
value = random.randint(0, 10000)
empty_sem.acquire()
mutex.acquire()
try:
index = shared_array.index(None)
except ValueError:
index = -1
if index != -1:
shared_array[index] = value
producers_activity_file.write(f"Producer {producer_id} -- produced item {production_number} with the value {value}\n")
print(f"Producer {producer_id} -- wrote to array and file")
mutex.release()
full_sem.release()
producers_activity_file.close()
# 1.b
def consumer(consumer_id):
while True:
full_sem.acquire()
mutex.acquire()
try:
index = shared_array.index(None, 0, ARRAY_SIZE)
except ValueError:
index = -1
if index == -1:
mutex.release()
full_sem.release()
break
value = shared_array[index]
shared_array[index] = None
# Write to screen
print(f"Consumer {consumer_id} -- consumed item {index + 1} with the value {value}")
# Write to file
consumers_activity_file.write(f"Consumer {consumer_id} -- consumed item {index + 1} with the value {value}\n")
print(f"Consumer {consumer_id} -- wrote to file")
mutex.release()
empty_sem.release()
consumers_activity_file.close()
# Create threads
producer_threads = [threading.Thread(target=producer, args=(i + 1,)) for i in range(NUM_PRODUCERS)]
consumer_threads = [threading.Thread(target=consumer, args=(i + 1,)) for i in range(NUM_CONSUMERS)]
# Start threads
for thread in producer_threads + consumer_threads:
thread.start()
# Wait for threads to finish
for thread in producer_threads + consumer_threads:
thread.join()
Editor is loading...
Leave a Comment