Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.6 kB
1
Indexable
Never
import threading
import random
import time

# Define constants
ARRAY_SIZE = 10
NUM_PRODUCERS = 3
NUM_CONSUMERS = 3
TOTAL_PRODUCTIONS = 10000

# Shared resources
shared_array = [None] * ARRAY_SIZE
producers_activity_file = open("Producers_activity.txt", "w")
consumers_activity_file = open("Consumers_activity.txt", "w")

# Semaphores
mutex = threading.Semaphore(1)  # Mutex for array access
full_sem = threading.Semaphore(0)  # Items produced and ready to consume
empty_sem = threading.Semaphore(ARRAY_SIZE)  # Empty slots in the array

# Function for producers
def producer(producer_id):
    for production_number in range(1, TOTAL_PRODUCTIONS + 1):
        # Produce item
        value = random.randint(0, 10000)

        # Enter critical section
        empty_sem.acquire()
        mutex.acquire()

        # Write to array
        index = shared_array.index(None)
        shared_array[index] = value

        # Write to file
        producers_activity_file.write(f"Producer {producer_id} -- produced item {production_number} with the value {value}\n")

        # Exit critical section
        mutex.release()
        full_sem.release()

    producers_activity_file.close()

# Function for consumers
def consumer(consumer_id):
    while True:
        # Enter critical section
        full_sem.acquire()
        mutex.acquire()

        # Read from array
        index = shared_array.index(None, 0, ARRAY_SIZE)
        if index == -1:
            break  # No more items to consume

        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")

        # Exit critical section
        mutex.release()
        empty_sem.release()

    consumers_activity_file.close()

# Create producer threads
producer_threads = []
for i in range(NUM_PRODUCERS):
    thread = threading.Thread(target=producer, args=(i + 1,))
    producer_threads.append(thread)
    thread.start()

# Create consumer threads
consumer_threads = []
for i in range(NUM_CONSUMERS):
    thread = threading.Thread(target=consumer, args=(i + 1,))
    consumer_threads.append(thread)
    thread.start()

# Wait for all producer threads to finish
for thread in producer_threads:
    thread.join()

# Wait for all consumer threads to finish
for thread in consumer_threads:
    thread.join()
Leave a Comment