Last active
February 22, 2022 20:24
-
-
Save tyler-8/e69d755f7c667ad7566bf37cef159bae to your computer and use it in GitHub Desktop.
This file contains 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 asyncio | |
def do_work_sync(seconds): | |
"""Wait 'seconds' using sync code""" | |
return asyncio.run(do_work_async(seconds, "sync")) | |
def organize_work_sync(work_inputs): | |
"""Execute multiple calls of the sync function""" | |
results = [do_work_sync(number) for number in work_inputs] | |
return results | |
async def do_work_async(seconds, work_type="async"): | |
"""Wait 'seconds' using async code""" | |
print(f"Waiting {seconds} seconds ({work_type})") | |
await asyncio.sleep(seconds) | |
return seconds ** seconds | |
async def organize_work_async(work_inputs): | |
"""Execute multiple calls of the async function""" | |
# Add 1 to the number to differentiate the results from the sync function | |
coroutines = [do_work_async(number + 1) for number in work_inputs] | |
results = await asyncio.gather(*coroutines) | |
return results | |
def start_work(): | |
"""Just a regular ol' sync function. Performs some sync tasks, then async, then more sync.""" | |
numbers = list(range(1, 3)) | |
# Start sync tasks, blocks until finished | |
results_sync1 = organize_work_sync(numbers) | |
# Start async tasks, blocks until finished (but performs all tasks asychronously) | |
results_async1 = asyncio.run(organize_work_async(numbers)) | |
# Start sync tasks, blocks until finished | |
results_sync2 = organize_work_sync(results_sync1) | |
# Start async tasks, blocks until finished (but performs all tasks asychronously) | |
results_async2 = asyncio.run(organize_work_async(results_sync1)) | |
print(results_sync1) | |
print(results_async1) | |
print(results_sync2) | |
print(results_async2) | |
if __name__ == "__main__": | |
start_work() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment