【问题标题】:Can I stop waiting for threads to finish if one of them produced results?如果其中一个产生结果,我可以停止等待线程完成吗?
【发布时间】:2020-08-06 07:34:51
【问题描述】:

我正在向不同服务器上大约数百个不同的 API 端点发出一堆 GET 请求。在这些端点之一中,有一些我想要获取并返回的信息。

在这些请求中的任何一个向我返回某些内容后,我想终止其他线程并退出。有些请求几乎是即时的,有些可能需要 20 秒才能完成。

如果我碰巧在 2 秒内找到信息,我不想等 20 秒后才能恢复工作。

目前我正在做这样的事情:

threads = list()
for s in silos: #here i create all the requests
    t = Thread(target=process_request, args=(my, args, here))
    t.name = "{} - {}".format(some, name)
    threads.append(t)

然后我做:

print("Threads: {}".format(len(threads))) # 100 - 250 of them
    [ t.start() for t in threads ]
    [ t.join() for t in threads ]

process_request() 如果 status_code == 200,则简单地发出 get 请求并将结果存储在 dict 中。 我正在使用请求和线程模块。

【问题讨论】:

    标签: python-3.x multithreading performance asynchronous concurrency


    【解决方案1】:

    如果您使用多进程池,那么您可以在第一个响应到达时立即终止该池:

    import multiprocessing as mp
    import time
    
    
    pool = None
    
    
    def make_get_request(inputs):
        print('Making get request with inputs ' + str(inputs))
        time.sleep(2)
        return 'dummy response for inputs ' + str(inputs)
    
    
    def log_response(response):
        print("Got response = " + response)
        pool.terminate()
    
    def main():
        global pool
        pool = mp.Pool()
        for i in range(10):
            pool.apply_async(make_get_request, args = (i,), callback = log_response)
        pool.close()
        pool.join()
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 2020-10-31
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 2011-07-10
      相关资源
      最近更新 更多