2016-01-27 65 views
0

首先我用ProcessPoolExecutor這樣的:python使用ProcessPoolExecutor easiliy?

def s(i): 
    time.sleep(1) 
    return i 

futs = [] 
with ProcessPoolExecutor(max_workers=10) as executor: 
    for i in range(WORKER_CNT): 
     print executor.submit(s, i,).result() 

但後來我發現這是不平行的,然後我改成這樣:

def s(i): 
    time.sleep(1) 
    return i 

futs = [] 
with ProcessPoolExecutor(max_workers=10) as executor: 
    for i in range(WORKER_CNT): 
     futs.append(executor.submit(s, i,)) 

for f in futs: 
    print f.result() 

之後我就開始擔心WORKER_CNT可太大,我需要等待多少時間看最後的結果,所以我改成這樣:

def s(i): 
    time.sleep(1) 
    return i 

futs = [] 
with ProcessPoolExecutor(max_workers=10) as executor: 
    for i in range(WORKER_CNT): 
     futs.append(executor.submit(s, i,)) 
     if len(futs) == 10: 
      for f in futs: 
       print f.result() 
      futs = [] 

這個時候,我可以處理10每次,我想知道我能做到這一點嗎?

回答

0

您要使用的Executor類的map方法

def s(i): 
    time.sleep(1) 
    return i 

with ProcessPoolExecutor(max_workers=10) as executor: 
    results = executor.map(s, range(WORKER_CNT)) 

它有一些其他選項來控制如何進行執行。

請注意,results而不是的一個列表。這是一個迭代器,它在計算時接收值。所以下面的代碼:

with ProcessPoolExecutor(max_workers=10) as executor: 
    for result in executor.map(s, range(WORKER_CNT)): 
     print(result) 

將只在內存中保留一個結果的時間,因爲他們是在幾分之一秒的消耗和花費更​​多的時間來生產。