3. pen4education
Motivacional
“É necessário a disciplina de um super humano
para escrever código legível baseado em
callbacks, se você não acredita em mim, olhe
qualquer pedaço de código javascript.”
4. pen4education
Motivacional
“É necessário a disciplina de um super humano
para escrever código legível baseado em
callbacks, se você não acredita em mim, olhe
qualquer pedaço de código javascript.”
Guido Van Rossum
10. pen4education
Event Loop
O Event Loop é o dispositivo central de execução.
● Registra, executar e cancela tarefas
● Cria servidores e clients para vários tipos de
comunicação (ex: sockets)
● Delega processos pesados a um executor. (ex:
ThreadPoolExecutor)
11. pen4education
Coroutine
Coroutine utiliza do statement yield do Python para
controlar a execução do código de uma função.
Sendo possível bloquear, continuar e realizar a
comunicação sem a necessidade de criação de
funções de callback.
12. pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
13. pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
14. pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
n total
1 None
15. pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
n total
1 10
16. pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
n total
2 30
17. pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
n total
2 30
18. pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
n total
2 30
19. pen4education
Task/Future
● Responsável pelo controle de execução de uma
corroutine.
● Contém importantes métodos como done(),
result() e cancel().
● Uma Task só é gerada pelo asyncio, utilizando
o asyncio.ensure_future() ou o loop.create_task
().
20. pen4education
import asyncio
async def loading():
i = 1
while True:
print('Loading ' + '.' * i)
await asyncio.sleep(0.5)
i += 1
async def run_very_long_task():
await asyncio.sleep(3)
return 42
async def supervisor():
loading_task = asyncio.ensure_future(loading()) # Cria task
content = await run_very_long_task() # Espera por retorno
loading_task.cancel() # Cancela execução da task
print('The result is {}'.format(content))
loop = asyncio.get_event_loop()
loop.run_until_complete(supervisor())
loop.close()
Task/Future
21. pen4education
import asyncio
async def loading():
i = 1
while True:
print('Loading ' + '.' * i)
await asyncio.sleep(0.5)
i += 1
async def run_very_long_task():
await asyncio.sleep(3)
return 42
async def supervisor():
loading_task = asyncio.ensure_future(loading()) # Cria task
content = await run_very_long_task() # Espera por retorno
loading_task.cancel() # Cancela execução da task
print('The result is {}'.format(content))
loop = asyncio.get_event_loop()
loop.run_until_complete(supervisor())
loop.close()
Task/Future
Loading .
Loading ..
Loading ...
Loading ....
Loading .....
Loading ......
The result is 42
22. pen4education
import asyncio
async def loading():
i = 1
while True:
print('Loading ' + '.' * i)
await asyncio.sleep(0.5)
i += 1
async def run_very_long_task():
await asyncio.sleep(3)
return 42
async def supervisor():
loading_task = asyncio.ensure_future(loading())
content = await run_very_long_task()
loading_task.cancel()
print('The result is {}'.format(content))
loop = asyncio.get_event_loop()
loop.run_until_complete(supervisor())
loop.close()
23. pen4education
import asyncio
async def loading():
i = 1
while True:
print('Loading ' + '.' * i)
await asyncio.sleep(0.5)
i += 1
async def run_very_long_task():
await asyncio.sleep(3)
return 42
async def supervisor():
loading_task = asyncio.ensure_future(loading())
content = await run_very_long_task()
loading_task.cancel()
print('The result is {}'.format(content))
loop = asyncio.get_event_loop()
loop.run_until_complete(supervisor())
loop.close()
24. pen4education
import asyncio
async def loading():
i = 1
while True:
print('Loading ' + '.' * i)
await asyncio.sleep(0.5)
i += 1
async def run_very_long_task():
await asyncio.sleep(3)
return 42
async def supervisor():
loading_task = asyncio.ensure_future(loading())
content = await run_very_long_task()
loading_task.cancel()
print('The result is {}'.format(content))
loop = asyncio.get_event_loop()
loop.run_until_complete(supervisor())
loop.close()