Search code examples
pythonconcurrencypython-multithreading

condition.wait() in a "with" block or self.acquire and self.release?


When using a condition variable, is it bad practice to use a with statement?

I know that condition.wait() releases the lock but does this behavior change if it's being called inside a with block?

class BlockingQueue:

    def __init__(self, size):
        self.max_size = size
        self.queue = deque()
        self.condition = Condition()

    # if there are already x items in queue, should block
    def enqueue(self, item):
        with self.condition:
            while len(self.queue) == self.max_size:
                self.condition.wait()
            self.queue.append(item)
            self.condition.notify_all()

Solution

  • The Condition object documentation says in part:

    A condition variable obeys the context management protocol: using the with statement acquires the associated lock for the duration of the enclosed block. The acquire() and release() methods also call the corresponding methods of the associated lock.

    So, yes, they work fine with a with statement. In fact that's the preferred way to make use of them.