如果列表中有项目,请不断检查列表并执行某些操作 [英] check a list constantly and do something if list has items

查看:90
本文介绍了如果列表中有项目,请不断检查列表并执行某些操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个全局列表,其中不断添加项目(来自网络客户端):

I have a global list where items are added constantly (from network clients):

mylist = []
def additem(uuid,work):
    mylist.append(uuid,work)

并且应该检查列表以及是否有项目的功能继续它们:

And a function which should check the list and if there are items proceed them:

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]

所以我希望你现在有个想法我尝试做什么,但我认为无限循环似乎不是正确的解决方案。

So I hope you get an idea now what I try to do, but I think the endless loop seems to be not the right solution.

推荐答案

在这种情况下,你必须使用多线程或多处理(取决于网络客户端是在不同的线程或不同的进程运行。

In this kind of case, you must have used either multithreading or multiprocessing (depending whether the network client is running at different thread or different process.

在任何一种情况下,你应该使用 队列 来管理传入的数据,然后之后存入 itemdone

In either case, you should use Queue to manage the incoming data, then store into itemdone afterwards.

您可以像这样定义队列:

You define the queue like this:

my_queue = queue.Queue() # or multiprocessing.Queue()

然后你应该在参数中包含队列(或者如果你使用线程,你可以像你一样使用全局队列)

Then later you should include the queue in the arguments (or if you use threading, you can use global queue, like you did)

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 函数插入特殊标记,并且 proceeditems 在收到特殊标记后,将退出循环。

To stop the whole process, you can make the additem function to insert special token, and the proceeditems, upon receiving the special token, will just quit the loop.

这篇关于如果列表中有项目,请不断检查列表并执行某些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆