Python block stream if list is empty

Is there a way to make the thread sleep if the list is empty and wake it up again when there are items? I do not want to use Queues, because I want to be able to index into the data structure.

+4
source share
2 answers

Yes, the solution will likely include a variable threading.Condition, as you noted in the comments.

Without additional information or a piece of code, it is difficult to understand which API is suitable for your needs. How do you create new elements? How do you consume them? Basically, you can do something like this:

cv = threading.Condition()
elements = []  # elements is protected by, and signaled by, cv

def produce(...):
  with cv:
    ... add elements somehow ...
    cv.notify_all()

def consume(...):
  with cv:
    while len(elements) == 0:
      cv.wait()
    ... remove elements somehow ...
+2
source

I would go with this:

import threading

class 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()
+1
source

Source: https://habr.com/ru/post/1649332/


All Articles