2017-08-14 33 views
1

下面的代码启动线程数和打印他们都做了之后的结果:如何从线程完成时获取结果?

import threading 

results = [None] * 5 
threads = [None] * 5 

def worker(i): 
    results[i] = i 

for i in range(5): 
    threads[i] = threading.Thread(target=worker, args=(i,)) 
    threads[i].start() 

# here I would like to use the results of the threads which are finished 
# while others still run 

for i in range(5): 
    threads[i].join() 

# here I have the results but only when all threads are done 
print(results) 

正如在代码中提到,我想用这些而另一些则仍在运行完线程的结果。 这样做的正确方法是什么?

我应该只是开始这将有while True:环和一个新的条目results连续检查或者是有这样操作的BUIL的机制(如threading.Thread调用,它会指向一个部分一个新的线程线程完成时的回调)?

+0

'进口ThreadPool',你可以把它从那里。 –

+0

你可以列举一下吗? –

+0

'https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python'可能是你的答案在这里 – Kallz

回答

1

由于您使用的Python 3,concurrent.futures是一个比threading更适合:

从multiprocessing.pool
import concurrent.futures 

results = [None] * 5 

def worker(i): 
    results[i] = i 

with concurrent.futures.ThreadPoolExecutor(5) as pool: 
    futmap = {pool.submit(worker, i): i for i in range(len(results))} 
    for fut in concurrent.futures.as_completed(futmap): 
     print("doing more stuff with", futmap[fut]) 
+0

* concurrent.futures模块为异步执行可调用对象提供了一个高级接口* - 非常好,这正是我所期待的,谢谢! – WoJ

相关问题