2013-11-27 55 views
1

我有一個全球性的列表,其中的項目不斷增加(從網絡客戶端):不斷檢查清單,並做一些事情,如果列表中有項目

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] 

所以我希望你現在是我嘗試做得到一個想法,但我覺得無限循環似乎是不正確的解決方案。

+0

也許[隊列](http://docs.python.org/2/library/queue.html)在這裏更好? –

+1

你想要一個無限循環...但你想要一個無盡的循環,等待某個東西,而不是儘可能快地旋轉。你可以使用'條件'......但如果你做對了,你會重現'隊列'確實是什麼,如果你沒有把握好(你不會這樣做,前30次左右),你會有一些無用的和痛苦的調試。 – abarnert

回答

3

在這種情況下,你必須使用,也可以多線程或者多(視網絡客戶端是否在不同的線程或者不同的進程中運行。

在這兩種情況下,你應該使用Queue管理輸入數據,然後存儲到itemdone事後

你這樣定義的隊列:

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

後來的後來,你應該包括參數的隊列(或者,如果你使用線程ING,你可以使用全局隊列,像你這樣)

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,收到了特殊標記,只會退出循環。

+0

是的,你是對的我使用gevent。隊列的問題是我需要爲所有項目運行somework函數,因爲有些可能工作,其他人不工作,我不能阻止隊列中可能工作的人。 – W0bble

+1

@ W0bble:好,'gevent'_isn't_多線程或多處理。但是答案基本上是一樣的,除了你想要一個['gevent.queue.Queue'](http://www.gevent.org/gevent.queue.html)而不是一個stdlib'queue.Queue'。 – abarnert

+0

@ W0bble:與此同時,「有些人可能會工作,其他人不工作,我不能阻止可能工作的人」作爲解釋你爲什麼不能使用隊列的解釋沒有任何意義。如果他們被困在隊列中,他們會以完全相同的方式陷入未同步列表中。沒有什麼區別,除了隊列實際上工作,而列表要求您刻錄CPU並具有競爭條件。 – abarnert

相關問題