SlideShare a Scribd company logo
1 of 28
Download to read offline
pen4education
Seu Primeiro Loop com AsyncIO
Carlos Maniero
Desenvolvedor Python na Loja Integrada
pen4education
Não tenha medo
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.”
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
pen4education
Motivacional
https://www.python.org/~guido/
pen4education
Polêmica
“Threads em Python são
excelentes em fazer nada.”
David Beazley
http://www.dabeaz.com/
pen4education
Hello World
import asyncio
async def hello_world():
print("Hello World!")
loop = asyncio.get_event_loop()
loop.run_until_complete(hello_world())
loop.close()
Python 3.5
pen4education
Hello World
import asyncio
@asyncio.coroutine
def hello_world():
print("Hello World!")
loop = asyncio.get_event_loop()
loop.run_until_complete(hello_world())
loop.close()
Python 3.4
pen4education
Py 3.4 vs Py 3.5
Python 3.4 Python 3.5
async def hello_world():
@asyncio.coroutine
def hello_world():
await x()yield from x()
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)
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.
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
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
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
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
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
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
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
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
().
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
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
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()
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()
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()
pen4education
import asyncio
import time
def slow_function():
time.sleep(3)
return 42
async def test1():
slow_function()
print('Finish test1')
async def test2():
for i in range(0, 10):
print(i)
await asyncio.sleep(0.5)
print('Finish test2')
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([
test1(),
test2()
]))
Bloqueio do Loop
Finish test1
0
1
2
3
4
5
6
7
8
9
Finish test2
pen4education
import asyncio
import time
def slow_function():
time.sleep(3)
return 42
async def test1():
await loop.run_in_executor(None, slow_function)
print('Finish test1')
async def test2():
for i in range(0, 10):
print(i)
await asyncio.sleep(0.5)
print('Finish test2')
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([
test1(),
test2()
]))
Bloqueio do Loop
0
1
2
3
4
5
Finish test1
6
7
8
9
Finish test2
pen4education
O que ver a seguir?
● ThreadPoolExecutor
● aioHTTP
pen4education
Obrigado <3
github.com/carlosmaniero
youtube.com/carlosmaniero
carlosmaniero@gmail.com

More Related Content

What's hot

C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency명신 김
 
Any event intro
Any event introAny event intro
Any event introqiang
 
An (abridged) Ruby Plumber's Guide to *nix
An (abridged) Ruby Plumber's Guide to *nixAn (abridged) Ruby Plumber's Guide to *nix
An (abridged) Ruby Plumber's Guide to *nixEleanor McHugh
 
Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow controlSimon Su
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184Mahmoud Samir Fayed
 
Node child process
Node child processNode child process
Node child processLearningTech
 
node.js workshop- node.js basics
node.js workshop- node.js basicsnode.js workshop- node.js basics
node.js workshop- node.js basicsQiong Wu
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practiceGuilherme Garnier
 
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIThe Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIEleanor McHugh
 
Perl: Coro asynchronous
Perl: Coro asynchronous Perl: Coro asynchronous
Perl: Coro asynchronous Shmuel Fomberg
 
Programa donde suma las filass de las dos columna y ordena el resultado de l...
Programa donde suma  las filass de las dos columna y ordena el resultado de l...Programa donde suma  las filass de las dos columna y ordena el resultado de l...
Programa donde suma las filass de las dos columna y ordena el resultado de l...Yo no soy perfecta pero soy mejor que tu
 
Mysql5.1 character set testing
Mysql5.1 character set testingMysql5.1 character set testing
Mysql5.1 character set testingPhilip Zhong
 

What's hot (20)

C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
 
Any event intro
Any event introAny event intro
Any event intro
 
An (abridged) Ruby Plumber's Guide to *nix
An (abridged) Ruby Plumber's Guide to *nixAn (abridged) Ruby Plumber's Guide to *nix
An (abridged) Ruby Plumber's Guide to *nix
 
Source Code
Source CodeSource Code
Source Code
 
Ch4
Ch4Ch4
Ch4
 
Anyevent
AnyeventAnyevent
Anyevent
 
Gevent rabbit rpc
Gevent rabbit rpcGevent rabbit rpc
Gevent rabbit rpc
 
Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow control
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184
 
Node child process
Node child processNode child process
Node child process
 
Cooking pies with Celery
Cooking pies with CeleryCooking pies with Celery
Cooking pies with Celery
 
Serverless stateful
Serverless statefulServerless stateful
Serverless stateful
 
node.js workshop- node.js basics
node.js workshop- node.js basicsnode.js workshop- node.js basics
node.js workshop- node.js basics
 
Clojure@Nuday
Clojure@NudayClojure@Nuday
Clojure@Nuday
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practice
 
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIThe Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
 
Perl: Coro asynchronous
Perl: Coro asynchronous Perl: Coro asynchronous
Perl: Coro asynchronous
 
Programa donde suma las filass de las dos columna y ordena el resultado de l...
Programa donde suma  las filass de las dos columna y ordena el resultado de l...Programa donde suma  las filass de las dos columna y ordena el resultado de l...
Programa donde suma las filass de las dos columna y ordena el resultado de l...
 
Programming
ProgrammingProgramming
Programming
 
Mysql5.1 character set testing
Mysql5.1 character set testingMysql5.1 character set testing
Mysql5.1 character set testing
 

Similar to Seu primeiro loop com Python AsyncIO - TDC 2016

BUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOBUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOMykola Novik
 
InterConnect: Server Side Swift for Java Developers
InterConnect:  Server Side Swift for Java DevelopersInterConnect:  Server Side Swift for Java Developers
InterConnect: Server Side Swift for Java DevelopersChris Bailey
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinAhmad Arif Faizin
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Futureemptysquare
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programováníPeckaDesign.cz
 
Codemania101: The Present, Past and Future of Asynchronous Programming in Python
Codemania101: The Present, Past and Future of Asynchronous Programming in PythonCodemania101: The Present, Past and Future of Asynchronous Programming in Python
Codemania101: The Present, Past and Future of Asynchronous Programming in PythonYothin Muangsommuk
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OBuzzcapture
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinAndrey Breslav
 
Implementing Virtual Machines in Ruby & C
Implementing Virtual Machines in Ruby & CImplementing Virtual Machines in Ruby & C
Implementing Virtual Machines in Ruby & CEleanor McHugh
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio Zoppi
 
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan GumbsSyncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan GumbsPôle Systematic Paris-Region
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
 
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPHOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPMykola Novik
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?PVS-Studio
 
Elixir/OTP for PHP developers
Elixir/OTP for PHP developersElixir/OTP for PHP developers
Elixir/OTP for PHP developersIgnacio Martín
 
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologiesit-people
 

Similar to Seu primeiro loop com Python AsyncIO - TDC 2016 (20)

BUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOBUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIO
 
InterConnect: Server Side Swift for Java Developers
InterConnect:  Server Side Swift for Java DevelopersInterConnect:  Server Side Swift for Java Developers
InterConnect: Server Side Swift for Java Developers
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlin
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
 
Codemania101: The Present, Past and Future of Asynchronous Programming in Python
Codemania101: The Present, Past and Future of Asynchronous Programming in PythonCodemania101: The Present, Past and Future of Asynchronous Programming in Python
Codemania101: The Present, Past and Future of Asynchronous Programming in Python
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
Implementing Virtual Machines in Ruby & C
Implementing Virtual Machines in Ruby & CImplementing Virtual Machines in Ruby & C
Implementing Virtual Machines in Ruby & C
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan GumbsSyncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
 
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPHOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
 
Elixir/OTP for PHP developers
Elixir/OTP for PHP developersElixir/OTP for PHP developers
Elixir/OTP for PHP developers
 
Mpi in-python
Mpi in-pythonMpi in-python
Mpi in-python
 
Gevent be or not to be
Gevent be or not to beGevent be or not to be
Gevent be or not to be
 
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
 
Asynchronous programming with django
Asynchronous programming with djangoAsynchronous programming with django
Asynchronous programming with django
 
Oop object oriented programing topics
Oop object oriented programing topicsOop object oriented programing topics
Oop object oriented programing topics
 

Recently uploaded

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 

Recently uploaded (20)

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Seu primeiro loop com Python AsyncIO - TDC 2016

  • 1. pen4education Seu Primeiro Loop com AsyncIO Carlos Maniero Desenvolvedor Python na Loja Integrada
  • 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
  • 6. pen4education Polêmica “Threads em Python são excelentes em fazer nada.” David Beazley http://www.dabeaz.com/
  • 7. pen4education Hello World import asyncio async def hello_world(): print("Hello World!") loop = asyncio.get_event_loop() loop.run_until_complete(hello_world()) loop.close() Python 3.5
  • 8. pen4education Hello World import asyncio @asyncio.coroutine def hello_world(): print("Hello World!") loop = asyncio.get_event_loop() loop.run_until_complete(hello_world()) loop.close() Python 3.4
  • 9. pen4education Py 3.4 vs Py 3.5 Python 3.4 Python 3.5 async def hello_world(): @asyncio.coroutine def hello_world(): await x()yield from x()
  • 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()
  • 25. pen4education import asyncio import time def slow_function(): time.sleep(3) return 42 async def test1(): slow_function() print('Finish test1') async def test2(): for i in range(0, 10): print(i) await asyncio.sleep(0.5) print('Finish test2') loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait([ test1(), test2() ])) Bloqueio do Loop Finish test1 0 1 2 3 4 5 6 7 8 9 Finish test2
  • 26. pen4education import asyncio import time def slow_function(): time.sleep(3) return 42 async def test1(): await loop.run_in_executor(None, slow_function) print('Finish test1') async def test2(): for i in range(0, 10): print(i) await asyncio.sleep(0.5) print('Finish test2') loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait([ test1(), test2() ])) Bloqueio do Loop 0 1 2 3 4 5 Finish test1 6 7 8 9 Finish test2
  • 27. pen4education O que ver a seguir? ● ThreadPoolExecutor ● aioHTTP