Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

deadlock in producer and consumer example #1

Open
@AraiYuno

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

        AltStyle によって変換されたページ (->オリジナル) /