我有一个全局列表,其中不断添加项目(来自网络客户端):
mylist = []
def additem(uuid,work):
mylist.append(uuid,work)
还有一个应该检查列表的函数,如果有项目就继续执行:
def proceeditems():
while True:
itemdone = []
if len(mylist) > 0:
for item in mylist:
try:
#This can go wrong and than need to be done again
result = gevent.spawn(somework(item))
#result returns the uuid
itemdone.append(result.value)
except:
pass
for item in itemdone:
mylist[:] = [value for value in mylist if value[0]!=item]
所以我希望你现在知道我想做什么,但我认为无限循环似乎不是正确的解决方案。
最佳答案
在这种情况下,您必须使用多线程或多处理(取决于网络客户端是否在不同线程或不同进程上运行。
无论哪种情况,您都应该使用 Queue
管理传入的数据,然后存储到 itemdone
中。
您可以这样定义队列:
my_queue = queue.Queue() # or multiprocessing.Queue()
然后你应该在参数中包含队列(或者如果你使用线程,你可以使用全局队列,就像你所做的那样)
def additem(uuid,work,the_queue):
the_queue.put((uuid,word)) # Queue in a tuple containing the data
def proceeditems(the_queue):
while True:
item = the_queue.get() # This will block until something is inside the queue
try:
result = somework(item)
itemdone.append(result)
except:
the_queue.put(item) # If failed, put back to queue for retry.
# You don't need the last two lines
要停止整个过程,可以让additem
函数插入特殊 token ,proceeditems
在收到特殊 token 后,将退出循环。
关于python - 不断检查列表并在列表中有项目时执行某些操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20231594/