以下代码启动几个线程并在完成后打印结果:
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}}调用哪个线程完成时会指向回调?)
答案 0 :(得分:1)
由于您使用的是Python 3,concurrent.futures
比threading
更合适:
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])