Use a queue: each thread when completed puts the result on the queue and then you just need to read the appropriate number of results and ignore the remainder:#!python3.3import queue # For Python 2.x use 'import Queue as queue'import threading, time, randomdef 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):Documentation for Queue.get() (with no arguments it is equivalent to 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 中完成您也可以使用 .join() 方法.python线程中join()的作用是什么You can to use .join() method too.what is the use of join() in python threading 这篇关于Python:如何让程序等到函数或方法完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-17 02:37
查看更多