Skip to content

Instantly share code, notes, and snippets.

@alekseyev
Last active December 21, 2015 05:28
Show Gist options
  • Save alekseyev/6256765 to your computer and use it in GitHub Desktop.
Save alekseyev/6256765 to your computer and use it in GitHub Desktop.
Concurrency in Python 3
# Source: http://firepear.net/docs/python3-futures-2.html
from concurrent.futures import ThreadPoolExecutor
import random
import time
def sleep_until_the_future(**kwargs):
kwargs['launchtime'] = time.time()
time.sleep(kwargs['sleeptime'])
return kwargs
def say_hello_from_the_future(future):
result = future.result()
now = time.time()
actualsleep = now - result['launchtime']
print("This is future {}.".format(result['futurenum']),
"I was created at {} and launched at {}.".format(result['createtime'], result['launchtime']),
"I was told to sleep for {} seconds.".format(result['sleeptime']),
"I woke up at {},".format(now),
"so I actually slept for {} seconds.".format(actualsleep))
def main():
executor = ThreadPoolExecutor(max_workers=10)
for i in range(20):
future = executor.submit(sleep_until_the_future,
futurenum=i,
sleeptime=(random.random() * 10),
createtime = time.time())
future.add_done_callback(say_hello_from_the_future)
for i in range(20):
time.sleep(1)
print("MAIN THREAD. Seconds elapsed: {}".format(i + 1))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment