Python block thread if list is empty Python block thread if list is empty multithreading multithreading

Python block thread if list is empty


Yes, the solution will probably involve a threading.Condition variable as you note in comments.

Without more information or a code snippet, it's difficult to know what API suits your needs. How are you producing new elements? How are you consuming them? At base, you could do something like this:

cv = threading.Condition()elements = []  # elements is protected by, and signaled by, cvdef produce(...):  with cv:    ... add elements somehow ...    cv.notify_all()def consume(...):  with cv:    while len(elements) == 0:      cv.wait()    ... remove elements somehow ...


I would go with this:

import threadingclass MyList (list):    def __init__(self, *args, **kwargs):        super().__init__(*args, **kwargs)        self._cond = threading.Condition()    def append(self, item):        with self._cond:            super().append(item)            self._cond.notify_all()    def pop_or_sleep(self):        with self._cond:            while not len(self):                self._cond.wait()            return self.pop()