如何在线程完成时从线程中获取结果?



以下代码启动几个线程,并在全部完成后打印结果:

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中的新条目,还是是否有用于此类操作的内置机制(作为线程完成后指向回调的threading.Thread调用的一部分(?

由于您使用的是 Python 3,因此concurrent.futuresthreading更适合:

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])

最新更新