2013-10-11 73 views
0

我有一個列表H = [item1, item2, item3....so on]和功能的每個項目,線程的Python爲列表

def start(item1): 
    p1 = Do something to item1  
    return p1 

我想要的功能開始應該並行運行在列表H.我知道多各項目,但我已經有4個使用多處理並行運行的列表。而如何實現列表中每個項目的線程可以實現?有人可以請示例代碼解釋這一點。

謝謝!

+0

http://docs.python.org/dev/library/concurrency.html –

回答

2

讓它運行在一個線程中給定函數,並將結果存儲功能:

import threading 
def run_item(f, item): 
    result_info = [threading.Event(), None] 
    def runit(): 
     result_info[1] = f(item) 
     result_info[0].set() 
    threading.Thread(target=runit).start() 
    return result_info 

然後另一個函數收集結果:

def gather_results(result_infos): 
    results = [] 
    for i in xrange(len(result_infos)): 
     result_infos[i][0].wait() 
     results.append(result_infos[i][1]) 
    return results 
從主線程

然後,說proc是處理物品的功能,items是您要處理的物品清單:

#start processing the items 
result_infos = [run_item(proc, item) for item in items] 
#gather the results (blocking) 
results = gather_results(result_infos) 

用法示例:

>>> import time 
>>> def proc(item): 
...  time.sleep(2.0) 
...  return item * 2 
... 
>>> print gather_results([run_item(proc, item) for item in [1, 2, 10, 100]]) 
#2 seconds later... 
[2, 4, 20, 200] 
+0

謝謝!這幫助我很多。還有一件事,如果我的列表包含10,000個項目,10,000個線程將並行運行?我們可以並行運行多少線程?我的清單包含近20,000件物品。 – user2766019

+0

@ user2766019:是的,這將運行與項目一樣多的線程。你絕對不想這樣做。你應該使用一個線程池,或者在某個地方保留一個計數器,所以如果有超過10個線程正在處理,你就等到你產生更多的線程。 – Claudiu

+0

嗨,真的很抱歉,但我是編程新手,無法獲取與上述代碼相關的threadpool的使用位置。你可以使用上面的代碼示例來解釋threadpool嗎?謝謝! – user2766019