【问题标题】:check a list constantly and do something if list has items不断检查列表,如果列表有项目,则执行某些操作
【发布时间】:2013-11-27 02:03:01
【问题描述】:

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

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 在这里更好?
  • 你确实想要一个无限循环……但你想要一个无限循环等待某事,而不是尽可能快地旋转。您可以为此使用Condition……但如果您做对了,您将准确复制Queue 所做的事情,如果您做错了(前30 次左右您不会做对) ),你将有一些无用和痛苦的调试。

标签: python list queue iteration gevent


【解决方案1】:

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

无论哪种情况,您都应该使用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函数插入特殊令牌,proceeditems收到特殊令牌后会退出循环。

【讨论】:

  • 是的,你是对的,我使用 gevent。队列的问题是我需要为所有项目运行 somework 函数,因为有些可能工作而另一些不工作,我无法阻止队列中可能工作的项目
  • @W0bble:嗯,gevent不是多线程或多处理。但答案基本上是一样的,只是你想要一个gevent.queue.Queue 而不是stdlib queue.Queue。
  • @W0bble:同时,“有些可能有效,有些无效,我无法阻止可能有效的那些”作为您不能使用队列的原因的解释没有任何意义。如果他们卡在队​​列中,他们将以完全相同的方式卡在未同步列表中。没有区别,只是队列实际工作,而列表需要你烧 CPU 并且有竞争条件。
  • @W0bble:最后,听起来您可能希望pool 的工作人员同时为任务提供服务,而不是一个只有一个工作人员为它服务的队列。但如果是这样,那就不难了。
  • 好的,谢谢你们,我会再次考虑队列选项。几个小时后,我忘记了为什么我一开始就把它扔掉了
猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 2014-06-18
  • 2017-06-08
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 2021-03-14
  • 1970-01-01
相关资源
最近更新 更多