Created
May 29, 2018 15:46
-
-
Save karakanb/df87954799ce9b6740b230da5480cde7 to your computer and use it in GitHub Desktop.
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 | |
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