Skip to content

deadlock in producer and consumer example #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
AraiYuno opened this issue Sep 22, 2024 · 0 comments
Open

deadlock in producer and consumer example #1

AraiYuno opened this issue Sep 22, 2024 · 0 comments

Comments

@AraiYuno
Copy link

AraiYuno commented Sep 22, 2024

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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant