Skip to content

Instantly share code, notes, and snippets.

@karakanb
Created May 29, 2018 15:46
Show Gist options
  • Save karakanb/df87954799ce9b6740b230da5480cde7 to your computer and use it in GitHub Desktop.
Save karakanb/df87954799ce9b6740b230da5480cde7 to your computer and use it in GitHub Desktop.
import concurrent.futures
import time
def function_to_execute_in_parallel(id):
# Function that takes long time.
time.sleep(abs(3 - id))
# Print id to test the order.
print("-- Processed id: %d -- " % id)
# Return the individual result.
return id * id
# Values to test in an array.
test_values = [1, 2, 3, 4, 5]
# Run the processes in paralel, max_workers denotes maximum number of processes in parallel.
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
# Create a dictionary of value: function_call pairs.
result_dict = {executor.submit(function_to_execute_in_parallel, value): value for value in test_values}
# Process results as completed.
for result_object in concurrent.futures.as_completed(result_dict):
test_value = result_dict[result_object]
print("Function result for value %d: %d" % (test_value, result_object.result()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment