【问题标题】:How to get results from threads as they complete?如何在线程完成时从线程中获取结果?
【发布时间】:2017-08-14 20:10:00
【问题描述】:

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

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 调用的一部分线程完成时会指向回调)?

【问题讨论】:

  • from multiprocessing.pool import ThreadPool 你可以从那里拿走。
  • 你能列举一下吗?
  • 'stackoverflow.com/questions/6893968/…' 可能你的答案就在这里
  • @cᴏʟᴅsᴘᴇᴇᴅ:谢谢,我会试试的。我希望有一个直接的回调机制(我在文档中没有找到)
  • @Kallz:我知道如何获取线程的结果(我的代码改编自您指向的链接的第二个答案)。如前所述,我一直在寻找一种回调机制,如果存在的话。

标签: python multithreading python-3.x


【解决方案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])

【讨论】:

  • concurrent.futures 模块为异步执行可调用对象提供了高级接口 - 太好了,这正是我想要的,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多