如果列表为空,则为Python块线程

时间:2016-07-27 20:08:26

标签: python multithreading list

如果列表为空,有没有办法让线程进入休眠状态,并在有项目时再次将其唤醒?我不想使用队列,因为我希望能够索引数据结构。

2 个答案:

答案 0 :(得分:2)

是的,解决方案可能会涉及您在评论中注明的threading.Condition变量。

如果没有更多信息或代码段,很难知道哪种API适合您的需求。你是如何制作新元素的?你是如何消费它们的?在基地,你可以做这样的事情:

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 ...

答案 1 :(得分:1)

我会这样做:

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