I am trying to write a function that sends multiple requests at once, and returns the first response. I am currently using a 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. 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