如果列表为空,则Python阻止线程
如果列表为空,是否有方法使线程进入睡眠状态,并在有项目时再次唤醒它?我不想使用队列,因为我希望能够索引到数据结构中。我会这样做:如果列表为空,则Python阻止线程,python,multithreading,list,Python,Multithreading,List,如果列表为空,是否有方法使线程进入睡眠状态,并在有项目时再次唤醒它?我不想使用队列,因为我希望能够索引到数据结构中。我会这样做: import threading class MyList (list): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._cond = threading.Condition() def append(sel
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()
是的,正如您在注释中所注意到的,解决方案可能会涉及一个变量 如果没有更多信息或代码片段,就很难知道什么API适合您的需要。你是如何产生新的元素的?你是怎么吃的?在base,您可以执行以下操作:
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 ...
@阿克沙马哈扬,我错了。我的意思是“列表”。但是如果我理解正确,你需要做一个循环,询问列表的状态。或者在设置列表时触发线程我将使用条件锁。如果可行,我将在这里发布我的解决方案。您可以创建一个列表子类,该子类上有一个锁,当列表中有项目时会打开。。。它既不快也不高效,但它应该有效