如何在线程完成时获得结果?

时间:2017-08-14 10:11:44

标签: python multithreading python-3.x

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

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中不断检查新条目,或者是否存在此类操作的内置机制(作为{的一部分) {1}}调用哪个线程完成时会指向回调?)

1 个答案:

答案 0 :(得分:1)

由于您使用的是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])