mrQWERTY
mrQWERTY

Reputation: 4149

Python block thread if list is empty

Is there a way to make a thread go to sleep if the list is empty and wake it up again when there are items? I don't want to use Queues since I want to be able to index into the datastructure.

Upvotes: 5

Views: 1989

Answers (2)

pilcrow
pilcrow

Reputation: 58681

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, cv

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

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

Upvotes: 3

Messa
Messa

Reputation: 25191

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

Upvotes: 1

Related Questions