Consumer/Producer multi-threading python

hello so i have this code

from threading import Thread
import queue
import threading
import time

class ConsumerProducer:
    def __init__(self):
        self.queue = Queue()
        self.lock = threading.Lock()
        self.fullQueueCondition = threading.Condition(self.lock)
        self.item = 0
    
    def Producer(self, items):
        self.lock.acquire()
        try:
            newItems = self.item + items
            self.item = newItems
            print("Producing: %d, new item number is %d \n" % (items, newItems))
            self.queue.get(newItems)
            self.fullQueueCondition.notifyAll()
        finally:
            self.lock.release()
            
    
    def Consumer(self, items):
        self.lock.acquire()
        try:
            while(self.item < items):
                self.fullQueueCondition.wait()
            newItems = self.item - items
            self.item = newItems
            print("consuming: %d, new item number is %d \n" % (items, newItems))
        finally:
            self.lock.release()
    
    def getitems(self):
        return self.item

def triggerProducer(basket, items, count):
    for i in range(count):
        basket.Producer(items)
        # time.sleep(1)

def triggerConsumer(basket, items, count):
    for i in range(count):
        basket.Consumer(items)
        # time.sleep(1)

if __name__ == '__main__':

    items = 5
    repetitions = 5
    threads = 10

    for i in range(threads):
        t1 = Thread(target=triggerProducer, args=(queue, items, repetitions,))
        t2 = Thread(target=triggerConsumer, args=(queue, items, repetitions,))
        t1.start()
        t2.start()

now one of the qualifications i need to meet is: the "add" method adds items to the queue; you cannot add if the queue becomes full; the "remove" method removes items from the queue; you cannot remove if the queue becomes empty)

Now I have that added but I feel like I'm not doing it correctly. Any sort of guidance would be appreciated.



Read more here: https://stackoverflow.com/questions/64902994/consumer-producer-multi-threading-python

Content Attribution

This content was originally published by user14262341 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: