Created
April 8, 2020 12:24
-
-
Save nitinbhojwani/568acff1206226757400086cdfb60d07 to your computer and use it in GitHub Desktop.
Using threadpool executor in Python3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import concurrent.futures | |
def test_function(n): | |
return n ** 2 | |
# initiate a thread pool executor | |
executor = concurrent.futures.ThreadPoolExecutor(max_workers=10) | |
# 1. submit jobs to the executor and track in a list | |
jobs = [] | |
for i in range(10): | |
jobs.append(executor.submit(test_function, i)) | |
for future in concurrent.futures.as_completed(jobs): | |
result = future.result() | |
print(result) | |
# do whatever you want to do here: | |
# if the exception is thrown from the child fn catch here | |
# 2. if we want to track the input or other identifier with the result, | |
# track the submitted jobs to the executor using a dict | |
jobs = {} | |
for id in range(10): | |
jobs[executor.submit(test_function, id)] = id | |
for future in concurrent.futures.as_completed(jobs): | |
id = jobs[future] # this reflects id above | |
result = future.result() | |
print(id, result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment