from threading import Thread, Condition import time import random queue = [] BUFF_SIZE = 10 condition = Condition() class ProducerThread(Thread): def run(self): nums = range(5) global queue while True: condition.acquire() if len(queue) == BUFF_SIZE: # Queue full, producer is waiting condition.wait() # Space in queue, Consumer notified the producer num = random.choice(nums) queue.append(num) print("Produced ", num) condition.notify() condition.release() time.sleep(random.random() * 2) class ConsumerThread(Thread): def run(self): global queue while True: condition.acquire() if not queue: # Nothing in queue, consumer is waiting condition.wait() # Producer added something to queue and notified the consumer num = queue.pop(0) print("Consumed ", num) condition.notify() condition.release() time.sleep(random.random() * 2) ProducerThread().start() ConsumerThread().start()