Last active
November 24, 2020 06:14
-
-
Save rscarrera27/f3796fc37cc7c3688d6983ae2ad50716 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 asyncio | |
async def factorial(name, number): | |
f = 1 | |
for i in range(2, number + 1): | |
print(f"Task {name}: Compute factorial({i})...") | |
await asyncio.sleep(1) | |
f *= i | |
print(f"Task {name}: factorial({number}) = {f}") | |
return name, f | |
async def main(): | |
tasks = [ | |
asyncio.create_task(c) for c in [ | |
factorial("A", 2), | |
factorial("B", 3), | |
factorial("C", 4), | |
]] | |
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) | |
if name == "A": | |
for t in pending: | |
t.cancel() | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment