Skip to content

Instantly share code, notes, and snippets.

@dbtorrico
Created June 19, 2019 18:51
Show Gist options
  • Save dbtorrico/8734d3b649f9d98ff6a5d0e3d14bd756 to your computer and use it in GitHub Desktop.
Save dbtorrico/8734d3b649f9d98ff6a5d0e3d14bd756 to your computer and use it in GitHub Desktop.
Mentoria python - AsyncIO
import asyncio
# Python 3.3 - Decorators
@asyncio.coroutine
def empacotar_bala():
print("Empacotando balas...")
# parada para verificar se tem cliente no balcão
yield from asyncio.sleep(0)
# troca de contexto
print("Explicitamente voltando a empacotar balas")
@asyncio.coroutine
def atender_balcao():
print("Explicitamente verificando se tem cliente no balcão...")
yield from asyncio.sleep(0)
print("Voltando a empacotar as balas")
# Python 3.5 - Async/Await nativo
async def empacotar_bala_native():
print("Empacotando balas...")
# parada para verificar se tem cliente no balcão
await asyncio.sleep(0)
# troca de contexto
print("Explicitamente voltando a empacotar balas")
async def atender_balcao_native():
print("Explicitamente verificando se tem cliente no balcão...")
await asyncio.sleep(0)
print("Voltando a empacotar as balas")
ioloop = asyncio.get_event_loop() # Event Loop
# Roda decorators
tasks = [ioloop.create_task(empacotar_bala()),
ioloop.create_task(atender_balcao())]
# Roda async/await
# tasks = [ioloop.create_task(empacotar_bala_native()),
# ioloop.create_task(atender_balcao_native())]
wait_tasks = asyncio.wait(tasks)
ioloop.run_until_complete(wait_tasks) # This will not return until all of the asynchronous methods are done.
ioloop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment