如何等待直到只有第一个线程在Python中完成 [英] How to wait until only the first thread is finished in Python

查看:257
本文介绍了如何等待直到只有第一个线程在Python中完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The requirement is to start five threads, and wait only in the fastest thread. All five threads went to look for the same data 5 directions, and one is enough to continue the control flow.

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

Actually, I need to wait for the first two threads to return, to verify against each other. But I guess if I know how to wait for the fastest. I can figure out how to wait for the second-fastest.

关于join(timeout)的话题很多,但是您并不事先知道要等待哪个(要先申请join).

A lot talk about join(timeout), but you don't know in advance which one to wait (which one to apply join in advance).

推荐答案

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

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.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):

Documentation for Queue.get() (with no arguments it is equivalent to Queue.get(True, None):

Queue.get([block [,timeout]])

Queue.get([block[, timeout]])

从以下位置删除并返回一个项目: 队列.如果可选的args块为true并且超时为None( 默认值),如果有必要,则阻止它,直到有可用的项目为止.如果超时是 一个正数,它最多会阻止超时秒,并提高 如果在此时间内没有可用的项目,则为空异常.否则 (块为false),如果有一个立即可用,则返回一个项目,否则返回 引发Empty异常(在这种情况下,超时将被忽略).

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中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆