使用队列:每个线程完成后将结果放入队列中,然后您只需读取适当数量的结果并忽略其余部分:
#!python3.3
import queue # For Python 2.x use 'import Queue as queue'
import threading, time, random
def func(id, result_queue):
print("Thread", id)
time.sleep(random.random() * 5)
result_queue.put((id, 'done'))
def main():
q = queue.Queue()
threads = [ threading.Thread(target=func, args=(i, q)) for i in range(5) ]
for th in threads:
th.daemon = True
th.start()
result1 = q.get()
result2 = q.get()
print("Second result: {}".format(result2))
if __name__=='__main__':
main()
Queue.get() 的文档(没有参数,它相当于 Queue.get(True, None):
Queue.get([block[, timeout]])
Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).
如何在Python中等待第一个线程完成 https://stackoverflow.com/questions/17564804/in-python-how-to-wait-until-only-the-first-thread-is-finished
您也可以使用 .join() 方法。python 线程中 join() 有什么用 https://stackoverflow.com/questions/15085348/what-is-the-use-of-join-in-python-threading