简体   繁体   English

如何在 python 中启动一个线程池并在一个线程池完成时停止?

[英]How to start a pool of threads and stop when one is finished in python?

I am trying to write a function that sends multiple requests at once, and returns the first response.我正在尝试编写一次发送多个请求并返回第一个响应的 function。 I am currently using a concurrent.futures.ThreadPoolExecutor object.我目前正在使用concurrent.futures.ThreadPoolExecutor object。 I understand that stopping a request in the middle is complicated, so instead I thought I could keep the other threads in the background and return a value early.我知道在中间停止请求很复杂,所以我认为我可以将其他线程保留在后台并尽早返回一个值。 However, the function seems to wait for the other threads to finish before returning.但是,function 似乎要等待其他线程完成后再返回。 How can I prevent that?我怎样才能防止这种情况? My code looks like this:我的代码如下所示:

def req(urls):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = []
        for url in urls:
            futures.append(executor.submit(get_request, url))
        for future in concurrent.futures.as_completed(futures):
            if future.result():
                return future.result()  # Other threads should stop now
    return False  # No valid response was sent

Try shutdown https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.shutdown尝试关闭https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.shutdown

def req(urls):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = []
        for url in urls:
            futures.append(executor.submit(get_request, url))
        for future in concurrent.futures.as_completed(futures):
            if future.result():
                executor.shutdown(wait=False, cancel_futures=True)
                return future.result()  # Other threads should stop now
    return False  # No valid response was sent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM