Open
Description
Since buffer_not_full
and lock
share the same lock, wouldn't with buffer_not_full
and with lock
within with buffer_not_full
contextmanager lead to a deadlock issue?
from threading import Thread, Lock, Condition
import time
from queue import Queue
# initialize buffer, shared by producer and consumer
buffer = Queue(maxsize=10)
# lock for controlled buffer access
lock = Lock()
# condition to signal when the buffer is not full/empty
buffer_not_full = Condition(lock)
buffer_not_empty = Condition(lock)
class Producer(Thread):
def run(self):
for i in range(100):
with buffer_not_full: # 1. acquires the lock
while buffer.full():
buffer_not_full.wait()
with lock: # 2. lock has been acquired by `buffer_not_full`, but attempts to obtain the same lock?
buffer.put(i)
print(f"Produced: {i}")
buffer_not_empty.notify()
class Consumer(Thread):
def run(self):
for i in range(100):
with buffer_not_empty:
while buffer.empty():
buffer_not_empty.wait()
with lock:
item = buffer.get()
print(f"Consumed: {item}")
buffer_not_full.notify()
# start producer and consumer threads
producer = Producer()
consumer = Consumer()
producer.start()
consumer.start()