The Python Oracle

How can I get the arguments I sent to ThreadPoolExecutor when iterating through future results?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Secret Catacombs

--

Chapters
00:00 Question
01:09 Accepted answer (Score 11)
01:32 Thank you

--

Full question
https://stackoverflow.com/questions/6336...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #multithreading #concurrency #concurrentfutures

#avk47



ACCEPTED ANSWER

Score 18


While submitting the task, you could create a mapping from future to its proxy.

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    future_proxy_mapping = {} 
    futures = []
    for proxy in proxies:
        future = executor.submit(is_proxy_alive, proxy)
        future_proxy_mapping[future] = proxy
        futures.append(future)
    
    for future in futures:
        proxy = future_proxy_mapping[future]
        print(proxy)
        print(future.result())



ANSWER 2

Score 0


You have appended to futures in the same order that you read from proxies, so they are in the same order, so you can just zip them up.

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    futures = []
    for proxy in proxies:
        future = executor.submit(is_proxy_alive, proxy)
        futures.append(future)
    
    for future, proxy in zip(futures, proxies):
        # do whatever