Last active
January 17, 2022 18:28
-
-
Save vhxs/e429ec9535204c9b485f1c14654ea3b0 to your computer and use it in GitHub Desktop.
How not to use asyncio
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 | |
import socket | |
async def alice(): | |
print("started alice") | |
# alice's task starts: she attempts to connect to Bob's server | |
while True: | |
try: | |
# this is where we try to connect to bob's server | |
# if the server hasn't started, we try again | |
# but we never reach the point of being able to try again (see bob's code) | |
conn = socket.create_connection(('127.0.0.1', 1337)) | |
except Exception as e: | |
print(f"got exception {e}, retrying...") | |
await asyncio.sleep(1) | |
# proceed with diffie-hellman, using conn to communicate with bob | |
print("alice never reaches this point") | |
async def bob(): | |
print("started bob") | |
# bob's task starts: he spins up a server and listens for incoming connections | |
sock = socket.create_server(('127.0.0.1', 1337)) | |
# this is a blocking call, which halts execution of the asyncio event loop | |
print("waiting for connections...") | |
conn, _ = sock.accept() | |
# this is where we would proceed with diffie-hellman, if we ever got to this point | |
print("bob never reaches this point") | |
async def main(): | |
# create tasks | |
run_alice = asyncio.create_task(alice()) | |
run_bob = asyncio.create_task(bob()) | |
# run them concurrently | |
await asyncio.gather(run_alice, run_bob) | |
if __name__ == '__main__': | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment