Skip to content

Instantly share code, notes, and snippets.

@gcrsaldanha

gcrsaldanha/concurrency.py

Last active Nov 25, 2020
Embed
What would you like to do?
Python concurrency example
import time # I will use it to simulate latency with time.sleep
from concurrent.futures import ThreadPoolExecutor, as_completed
def has_facebook_account(user_email):
time.sleep(5) # 5 seconds! That is bad.
print("Finished facebook after 5 seconds!")
return True
def has_github_account(user_email):
time.sleep(1) # 1 second. Phew!
print("Finished github after 1 second!")
return True
def has_twitter_account(user_email):
time.sleep(3) # Well...
print("Finished twitter after 3 seconds!")
return False
# Main method that answers if an user has an account in any of the platforms
def has_social_account(user_email):
# ThreadPoolExecutor is a subclass of Executor that uses threads.
# max_workers is the max number of threads that will be used.
# Since we are scheduling only 3 tasks, it does not make sense to have
# more than 3 threads, otherwise we would be wasting resources.
executor = ThreadPoolExecutor(max_workers=3)
# Schedule (submit) 3 tasks (one for each social account check)
# .submit method returns a Future object
facebook_future = executor.submit(has_facebook_account, user_email)
twitter_future = executor.submit(has_twitter_account, user_email)
github_future = executor.submit(has_github_account, user_email)
future_list = [facebook_future, github_future, twitter_future]
# as_completed receives an iterable of Future objects
# and yields each future once it has been completed.
for future in as_completed(future_list):
# .result() returns the future object return value
future_return_value = future.result()
print(future_return_value)
if future_return_value is True:
# I can early return once any result is True
return True
user_email = "user@email.com"
if __name__ == '__main__':
has_social_account(user_email)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment