gpt4 book ai didi

python - 如何等到只有第一个线程在 Python 中完成

转载 作者:太空狗 更新时间:2023-10-29 17:03:52 25 4
gpt4 key购买 nike

要求是启动五个线程,只在最快的线程中等待。所有五个线程都去 5 个方向寻找相同的数据,一个就足以继续控制流。

实际上,我需要等待前两个线程返回,以相互验证。但我想如果我知道如何等待最快。我可以弄清楚如何等待第二快的。

多谈join(timeout) , 但你事先并不知道要等待哪一个(提前申请哪个 join)。

最佳答案

使用队列:每个线程完成后将结果放入队列,然后您只需要读取适当数量的结果并忽略其余部分:

#!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 - 如何等到只有第一个线程在 Python 中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17564804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com