SlideShare a Scribd company logo
Async 
Programming and 
Python 
PyCon India, 2014 
Chetan Giridhar
Basics 
• Programming tasks: 
o I/O bound 
o CPU bound 
• Say, you’re doing I/O 
o Will it complete immediately? When will it be done? 
o Wont they block you?
Blocking I/O: Example 
import requests 
r = requests.get(‘http://google.co.in’) 
r.status_code 
• What if the request takes a long time? 
• Operation blocks until all the data is recieved from the server 
Can we do something in the meanwhile? 
Can we run another task, concurrently?
Non Blocking / Async 
• Non-blocking means the ability to make continuous 
progress at all times 
• Resources needed for a response must not be 
monopolized 
• As such it can enable both lower latency, higher 
throughput
Programming Models 
Synchronous model 
time 
time 
time 
Threaded model 
Asynchronous model 
Task 1 Task 2 Task 3
Math 
• Task = make a call to http://ip.jsontest.com 
• Say, Task = Task1 = Task2 = Task 3 = 400ms 
• Sync Model 
o Time taken = Task1+ Task2 + Task3 = 1.2 sec 
• Threaded Model 
o Time taken = 510 ms 
• Async Model 
o Time taken = 460 ms 
What’s the 
magic here?
Async Paradigm 
• Clients requests the event driven web server; 
• requests are processed by event loop; 
• event handlers cater to events with callbacks 
Client Event driven server I/O loop 
Event driven I/O loop 
Request 
IO loop handles 
request 
Event Handlers
Reactor Pattern 
• Typical non blocking frameworks work on a 
philosophy of single threaded event loop 
o keeps polling for events 
Reactor 
Pattern 
Waiting for Events 
Handling Events
More Details! 
• Framework typically maintains a list of file 
descriptors(fd), events to monitor and 
corresponding event handlers for each of the fd 
• Listening to events on a fd is a kernel space task 
o epoll, [kqueue/select] – libraries provide event notifications in a non-blocking 
way 
• Epoll watches file descriptors (sockets) and returns 
needed (READ, WRITE & ERROR) events
Async way 
• Async strategy aims for: 
o Making I/O tasks non blocking 
o I/O tasks would run independently 
o generate an event when tasks are complete 
o with help of callbacks 
• Benefits 
o No need to wait till blocking I/O tasks are complete 
o More responsive real time applications 
o Thread safety isn't an issue 
• Can we solve any other Python problems with this 
mechanism? 
o Eliminating GIL?
Async in Python 
• Frameworks 
o Tornado 
o Twisted 
o Gevent 
• Modules 
o Tulip 
o Asyncio
Async in Python 
• Frameworks 
o Tornado 
o Twisted 
o Gevent 
• Modules 
o Tulip 
o Asyncio
Asyncio 
• Part of Python library 
o The latest module for async application development 
• Only for Python > 3.4 
o Incompatible with prior versions 
• A whole new way to development 
o Let’s you write self contained, synchronous looking tasks 
o Run two infinite loops at the same time on the same thread 
• Works with other framework 
o Tornado, Twisted, GEvent
Asyncio… 
• Write single threaded concurrent code 
• Principle of Interleaved execution of subroutines 
• Co-operative scheduling 
o Only one task at a time 
• Based on libevent 
o Select, kpoll, kqueue
Asyncio: Components 
Event loop 
Co-routines, Futures, Tasks 
Transports, Protocols
Asyncio: Components 
• Event loop 
o Register, executing and cancelling calls 
o Schedule execution of a task (co-routine) 
o Creates transport (async client and server) 
o Runs I/O callbacks (Watches file descriptors) 
o Thread interface 
o [BaseEventLoop.create_task()] or async() 
o [asyncio.get_event_loop()]
Asyncio: Components 
• Co-routine 
o Generator (“yield from”) 
o suspended at preset execution points, and 
o resumed later by keeping track of local state 
o @coroutine decorator
Asyncio: Components 
• Task 
o responsible for executing a coroutine 
o If coroutine yields from a future, the task suspends the execution of the 
coroutine and waits for the future 
o coroutine restarts when future is done 
o Subclass of class Future 
o [async(coroutine)] 
o BaseEventLoop.create_task(coro)
Asyncio: Components 
• Future 
o A class 
o for results that are 
available later 
import asyncio 
@asyncio.coroutine 
def slow_operation(future): 
yield from asyncio.sleep(1) <- Co-routine suspend 
future.set_result('Future is done!') 
def got_result(future): 
print(future.result()) 
loop.stop() 
loop = asyncio.get_event_loop() <- Event loop 
future = asyncio.Future() <- Future object 
asyncio.async(slow_operation(future)) <- Task 
future.add_done_callback(got_result) 
try: 
loop.run_forever() 
finally: 
loop.close()
Asyncio: Components 
• transport 
o represent connections such as sockets, SSL connection and pipes 
o Async socket operations 
• Usually frameworks implement e.g. Tornado 
• protocols 
o represent applications such as HTTP client/server, SMTP, and FTP 
o Async http operation 
o [loop.create_connection()]
Example: Asyncio Redis 
import asyncio 
import asyncio_redis 
@asyncio.coroutine 
def my_subscriber(channels): 
connection = yield from asyncio_redis.Connection.create(host='localhost', port=6379) 
subscriber = yield from connection.start_subscribe() 
yield from subscriber.subscribe(channels) 
while True: 
reply = yield from subscriber.next_published() 
print('Received: ', repr(reply.value), 'on channel', reply.channel) 
loop = asyncio.get_event_loop() 
asyncio.async(my_subscriber('channel-1')) 
asyncio.async(my_subscriber('channel-2')) 
loop.run_forever()
Example: Asyncio ‘Tasks’ 
import asyncio 
@asyncio.coroutine 
def factorial(name, number): 
f = 1 
for i in range(2, number+1): 
print("Task %s: Compute factorial(%s)..." % (name, i)) 
yield from asyncio.sleep(1) 
f *= i 
print("Task %s: factorial(%s) = %s" % (name, number, f)) 
loop = asyncio.get_event_loop() 
tasks = [ 
asyncio.async(factorial("A", 2)), 
asyncio.async(factorial("B", 3)), 
asyncio.async(factorial("C", 4))] 
loop.run_until_complete(asyncio.wait(tasks)) 
loop.close()
Async in Python 
• Frameworks 
o Tornado 
o Twisted 
o Gevent 
• Modules 
o Tulip 
o Asyncio
Tornado Async 
• Event Loop => tornado.ioloop 
• Coroutine => tornado.gen.coroutine 
• Future => tornado.concurrent.future 
• Transport/Protocol => tornado.iostream 
• Bridge the gap => tornado.platform.asyncio – 
Combines asyncio and tornado in same event loop
Tornado Async Http 
import tornado.ioloop 
from tornado.httpclient import AsyncHTTPClient 
def handle_request(response): 
'''callback needed when a response arrive''' 
if response.error: 
print("Error:", response.error) 
else: 
print(’Success') 
print(response.body) 
Before Event Loop Starts! 
Success 
b'{"ip": "117.192.252.80"}n' 
Callback 
http_client = AsyncHTTPClient() # initialize http client 
http_client.fetch(” http://ip.jsontest.com/", handle_request) 
print("Before Event Loop Starts!") 
tornado.ioloop.IOLoop.instance().start() # start the tornado ioloop
Tornado Coroutine 
import tornado.web 
import tornado.gen 
from tornado.httpclient import AsyncHTTPClient 
class GenAsyncHandler(tornado.web.RequestHandler): 
@tornado.gen.coroutine 
def get(self): 
http_client = AsyncHTTPClient() 
response = yield http_client.fetch("http://google.com") 
print(response) 
application = tornado.web.Application([ (r"/", 
GenAsyncHandler), ]) 
if __name__ == "__main__": 
application.listen(8888) 
tornado.ioloop.IOLoop.instance().start() 
gen.coroutine schedules the generator 
to be resumed when the Future is 
resolved 
‘yield’ makes the function a generator 
The generator in turn returns a Future 
instance 
In this case, response, will resolve with 
response from fetch or an exception
Tornado Engine 
class MainHandlerAsync(tornado.web.RequestHandler): 
@tornado.web.asynchronous 
@tornado.gen.engine 
def get(self): 
req = tornado.httpclient.HTTPRequest("http://127.0.0.1:8888/",) 
client = tornado.httpclient.AsyncHTTPClient() 
response = yield tornado.gen.Task(client.fetch, req) 
self.finish() 
application = tornado.web.Application([ 
(r"/async", MainHandlerAsync), 
]) 
if __name__ == "__main__": 
http_server = tornado.httpserver.HTTPServer(application) 
http_server.listen(8888) 
tornado.ioloop.IOLoop.instance().start()
Let’s create our Future! 
myfuture.py server.py 
import time 
import datetime 
from tornado.concurrent import return_future 
class AsyncHTTPClient(object): 
@return_future 
def fetch(self, url, callback=None): 
print("In my fetch") 
time.sleep(0.02) 
result = str(datetime.datetime.utcnow()) 
callback(result) 
import tornado.web 
import tornado.gen 
from myfuture import AsyncHTTPClient 
def test(arg): 
print('In test:' + arg) 
class GenAsync(tornado.web.RequestHandler): 
@tornado.gen.coroutine 
def get(self): 
http_client = AsyncHTTPClient() 
r = yield http_client.fetch(“http://google.com”,test) 
print(r) 
application = tornado.web.Application([ 
(r"/", GenAsync),]) 
if __name__ == "__main__": 
application.listen(8888) 
tornado.ioloop.IOLoop.instance().start()
Performance: 
Blocking vs Async
Work to be achieved
Performance Results 
ab -n 500 -c 10 http://localhost:8888/blocking 
ab -n 500 -c 10 http://localhost:8888/async 
6000 
5000 
4000 
3000 
2000 
1000 
0 
Time per request 
Async Blocking 
Async 
Blocking 
200 
150 
100 
50 
0 
Requests per second 
Async Blocking 
Async 
Blocking
Learnings 
• Async programming is an efficient, easy to 
understand design and code 
• Python asyncio module is comprehensive 
• Has generic use cases for vast variety of 
applications 
o Responsive web applications 
o Networking applications 
• Requires a new way to program and design
Recommendations 
• Async programming is not a holistic solution 
• It has its own pros and cons 
o Suitable for primarily I/O bound applications 
o Needs enough tasks available to run 
• asyncio module is only available for Python 3 
applications 
• Also explore other methods of concurrency: 
o Eventlets 
o STM 
o Multiprocessing/threads 
o Special languages e.g. GO, Scala 
• Understand and use 
References 
• asyncio – http://python.org 
• Python asyncio – 
o http://www.buzzcapture.com 
o www.slideshare.net/saghul 
• Tornado – http://tornadoweb.org 
• Multithreading – www.drdobbs.com 
• Event loop: https://docs.python.org/3/library/asyncio-eventloop. 
html
Contact Us 
• Chetan Giridhar 
o www.technobeans.com 
o https://github.com/cjgiridhar 
• Vishal Kanaujia 
o www.freethreads.wordpress.com 
o https://github.com/vishalkanaujia
Backup
Asyncio: example 
import asyncio 
@asyncio.coroutine 
def create(): 
yield from asyncio.sleep(3.0) 
print("(1) create file") 
@asyncio.coroutine 
def write(): 
yield from asyncio.sleep(1.0) 
print("(2) write into file") 
@asyncio.coroutine 
def close(): 
print("(3) close file") 
@asyncio.coroutine 
def test(): 
asyncio.async(create()) 
asyncio.async(write()) 
asyncio.async(close()) 
yield from asyncio.sleep(2.0) 
loop.stop() 
loop = asyncio.get_event_loop() 
asyncio.async(test()) 
loop.run_forever() 
print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop)) 
loop.close()
Python Async Modules 
• Asynccore 
• Asyncchat 
• Gevent 
• Twisted 
• Eventlets
Concurrency Techniques 
• Multithreading/processing 
• Green Threads 
• STM
Tornado + AsyncIO 
from tornado.platform.asyncio import AsyncIOMainLoop 
from tornado.httpclient import AsyncHTTPClient 
import asyncio 
AsyncIOMainLoop().install() -- # Tell Tornado to use the asyncio eventloop 
loop = asyncio.get_event_loop() -- # get the loop 
http_client = AsyncHTTPClient() -- # the Tornado HTTP client 
def aio_fetch(client, url, **kwargs): 
fut = asyncio.Future() 
client.fetch(url, callback=fut.set_result, **kwargs) 
return fut 
@asyncio.coroutine 
def main(): 
print("fetching my site") 
mysite = yield from aio_fetch(http_client, "http://google.com/") 
print("hello httpbin") 
httpbin = yield from aio_fetch(http_client, "http://httpbin.org?q=%d" % mysite.code) 
print(httpbin.body) 
loop.run_until_complete(main())
Co-routine v/s Callback 
import asyncio 
def just_print_messages(loop): 
print('Just print') 
loop.call_later(1, just_print_messages, loop) 
def main(): 
loop = asyncio.get_event_loop() 
try: 
loop.call_soon(just_print_messages, loop) 
loop.run_forever() 
finally: 
loop.close() 
if __name__ == '__main__': 
main() 
import asyncio 
@asyncio.coroutine 
def just_print_messages(): 
while True: 
print('Just print') 
yield from asyncio.sleep(1) 
def main(): 
loop = asyncio.get_event_loop() 
try: 
loop.run_until_complete(just_print_messages()) 
finally: 
loop.close() 
if __name__ == '__main__': 
main()
Async in NodeJS 
request is an 
var http = require(‘http’); 
event 
var server = http.createServer; 
server.on(‘request’, function(request,response) { 
response.writeHead(200); 
response.end(‘Hello World’); 
}).listen(8001); 
Callback 
console.log(‘Server running on port 8001’);

More Related Content

What's hot (20)

PHPとシグナル、その裏側
PHPとシグナル、その裏側PHPとシグナル、その裏側
PHPとシグナル、その裏側
do_aki
 
The Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventureThe Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventure
mylittleadventure
 
NumPyが物足りない人へのCython入門
NumPyが物足りない人へのCython入門NumPyが物足りない人へのCython入門
NumPyが物足りない人へのCython入門
Shiqiao Du
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
AnirudhaGaikwad4
 
ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!
Mr. Vengineer
 
DWARF Data Representation
DWARF Data RepresentationDWARF Data Representation
DWARF Data Representation
Wang Hsiangkai
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
Roberto Casadei
 
Rust programming-language
Rust programming-languageRust programming-language
Rust programming-language
Mujahid Malik Arain
 
PyTorch Introduction
PyTorch IntroductionPyTorch Introduction
PyTorch Introduction
Yash Kawdiya
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
Rodolfo Finochietti
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
Bo-Yi Wu
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
Joshua Zhu
 
[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅
NAVER D2
 
Semmle Codeql
Semmle Codeql Semmle Codeql
Semmle Codeql
M. S.
 
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
PgDay.Seoul
 
OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015
OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015
OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015
Toru Yamaguchi
 
0章 Linuxカーネルを読む前に最低限知っておくべきこと
0章 Linuxカーネルを読む前に最低限知っておくべきこと0章 Linuxカーネルを読む前に最低限知っておくべきこと
0章 Linuxカーネルを読む前に最低限知っておくべきこと
mao999
 
Python idle introduction(3)
Python idle introduction(3)Python idle introduction(3)
Python idle introduction(3)
Fahad Ashrafi
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming language
robin_sy
 
The Internals of "Hello World" Program
The Internals of "Hello World" ProgramThe Internals of "Hello World" Program
The Internals of "Hello World" Program
National Cheng Kung University
 
PHPとシグナル、その裏側
PHPとシグナル、その裏側PHPとシグナル、その裏側
PHPとシグナル、その裏側
do_aki
 
The Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventureThe Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventure
mylittleadventure
 
NumPyが物足りない人へのCython入門
NumPyが物足りない人へのCython入門NumPyが物足りない人へのCython入門
NumPyが物足りない人へのCython入門
Shiqiao Du
 
ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!
Mr. Vengineer
 
DWARF Data Representation
DWARF Data RepresentationDWARF Data Representation
DWARF Data Representation
Wang Hsiangkai
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
Roberto Casadei
 
PyTorch Introduction
PyTorch IntroductionPyTorch Introduction
PyTorch Introduction
Yash Kawdiya
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
Rodolfo Finochietti
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
Bo-Yi Wu
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
Joshua Zhu
 
[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅
NAVER D2
 
Semmle Codeql
Semmle Codeql Semmle Codeql
Semmle Codeql
M. S.
 
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
PgDay.Seoul
 
OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015
OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015
OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015
Toru Yamaguchi
 
0章 Linuxカーネルを読む前に最低限知っておくべきこと
0章 Linuxカーネルを読む前に最低限知っておくべきこと0章 Linuxカーネルを読む前に最低限知っておくべきこと
0章 Linuxカーネルを読む前に最低限知っておくべきこと
mao999
 
Python idle introduction(3)
Python idle introduction(3)Python idle introduction(3)
Python idle introduction(3)
Fahad Ashrafi
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming language
robin_sy
 

Viewers also liked (20)

PyCon India 2012: Rapid development of website search in python
PyCon India 2012: Rapid development of website search in pythonPyCon India 2012: Rapid development of website search in python
PyCon India 2012: Rapid development of website search in python
Chetan Giridhar
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
Saúl Ibarra Corretgé
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
Lukasz Dobrzanski
 
Asynchronous web-development with Python
Asynchronous web-development with PythonAsynchronous web-development with Python
Asynchronous web-development with Python
Anton Caceres
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
Saúl Ibarra Corretgé
 
Разработка сетевых приложений с gevent
Разработка сетевых приложений с geventРазработка сетевых приложений с gevent
Разработка сетевых приложений с gevent
Andrey Popp
 
Vert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingVert.x – The problem of real-time data binding
Vert.x – The problem of real-time data binding
Alex Derkach
 
Cubes – pluggable model explained
Cubes – pluggable model explainedCubes – pluggable model explained
Cubes – pluggable model explained
Stefan Urbanek
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3Asynchronous I/O in Python 3
Asynchronous I/O in Python 3
Feihong Hsu
 
Python on Rails 2014
Python on Rails 2014Python on Rails 2014
Python on Rails 2014
Albert O'Connor
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
Jim Yeh
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
Victor Stinner
 
Asyncio
AsyncioAsyncio
Asyncio
Andrew Svetlov
 
Python class
Python classPython class
Python class
건희 김
 
Bubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsBubbles – Virtual Data Objects
Bubbles – Virtual Data Objects
Stefan Urbanek
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
Chetan Giridhar
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
Saúl Ibarra Corretgé
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
Saúl Ibarra Corretgé
 
Comandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocerComandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocer
Geek Advisor Freddy
 
Python master class 3
Python master class 3Python master class 3
Python master class 3
Chathuranga Bandara
 
PyCon India 2012: Rapid development of website search in python
PyCon India 2012: Rapid development of website search in pythonPyCon India 2012: Rapid development of website search in python
PyCon India 2012: Rapid development of website search in python
Chetan Giridhar
 
Asynchronous web-development with Python
Asynchronous web-development with PythonAsynchronous web-development with Python
Asynchronous web-development with Python
Anton Caceres
 
Разработка сетевых приложений с gevent
Разработка сетевых приложений с geventРазработка сетевых приложений с gevent
Разработка сетевых приложений с gevent
Andrey Popp
 
Vert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingVert.x – The problem of real-time data binding
Vert.x – The problem of real-time data binding
Alex Derkach
 
Cubes – pluggable model explained
Cubes – pluggable model explainedCubes – pluggable model explained
Cubes – pluggable model explained
Stefan Urbanek
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3Asynchronous I/O in Python 3
Asynchronous I/O in Python 3
Feihong Hsu
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
Jim Yeh
 
Bubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsBubbles – Virtual Data Objects
Bubbles – Virtual Data Objects
Stefan Urbanek
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
Chetan Giridhar
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
Saúl Ibarra Corretgé
 
Comandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocerComandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocer
Geek Advisor Freddy
 
Ad

Similar to Async programming and python (20)

Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
Praveen Gollakota
 
Webscraping with asyncio
Webscraping with asyncioWebscraping with asyncio
Webscraping with asyncio
Jose Manuel Ortega Candel
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
Gary Yeh
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
Betclic Everest Group Tech Team
 
Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...
Baruch Sadogursky
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Baruch Sadogursky
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
ahmed sayed
 
AsyncIO To Speed Up Your Crawler
AsyncIO To Speed Up Your CrawlerAsyncIO To Speed Up Your Crawler
AsyncIO To Speed Up Your Crawler
Linggar Primahastoko
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
vfabro
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
Piotr Pelczar
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
Marcin Tyborowski
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
Riccardo Terrell
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
Luciano Mammino
 
Async Web Frameworks in Python
Async Web Frameworks in PythonAsync Web Frameworks in Python
Async Web Frameworks in Python
Ryan Johnson
 
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
Mykola Novik
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python Asyncio
Nathan Van Gheem
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Codemotion
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
Lucio Grenzi
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
Oliver Scheer
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
Praveen Gollakota
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
Gary Yeh
 
Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...
Baruch Sadogursky
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Baruch Sadogursky
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
ahmed sayed
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
vfabro
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
Piotr Pelczar
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
Marcin Tyborowski
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
Luciano Mammino
 
Async Web Frameworks in Python
Async Web Frameworks in PythonAsync Web Frameworks in Python
Async Web Frameworks in Python
Ryan Johnson
 
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
Mykola Novik
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python Asyncio
Nathan Van Gheem
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Codemotion
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
Lucio Grenzi
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
Oliver Scheer
 
Ad

More from Chetan Giridhar (7)

Rapid development & integration of real time communication in websites
Rapid development & integration of real time communication in websitesRapid development & integration of real time communication in websites
Rapid development & integration of real time communication in websites
Chetan Giridhar
 
Fuse'ing python for rapid development of storage efficient FS
Fuse'ing python for rapid development of storage efficient FSFuse'ing python for rapid development of storage efficient FS
Fuse'ing python for rapid development of storage efficient FS
Chetan Giridhar
 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python
Chetan Giridhar
 
Testers in product development code review phase
Testers in product development   code review phaseTesters in product development   code review phase
Testers in product development code review phase
Chetan Giridhar
 
Design patterns in python v0.1
Design patterns in python v0.1Design patterns in python v0.1
Design patterns in python v0.1
Chetan Giridhar
 
PyCon India 2011: Python Threads: Dive into GIL!
PyCon India 2011: Python Threads: Dive into GIL!PyCon India 2011: Python Threads: Dive into GIL!
PyCon India 2011: Python Threads: Dive into GIL!
Chetan Giridhar
 
Pycon11: Python threads: Dive into GIL!
Pycon11: Python threads: Dive into GIL!Pycon11: Python threads: Dive into GIL!
Pycon11: Python threads: Dive into GIL!
Chetan Giridhar
 
Rapid development & integration of real time communication in websites
Rapid development & integration of real time communication in websitesRapid development & integration of real time communication in websites
Rapid development & integration of real time communication in websites
Chetan Giridhar
 
Fuse'ing python for rapid development of storage efficient FS
Fuse'ing python for rapid development of storage efficient FSFuse'ing python for rapid development of storage efficient FS
Fuse'ing python for rapid development of storage efficient FS
Chetan Giridhar
 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python
Chetan Giridhar
 
Testers in product development code review phase
Testers in product development   code review phaseTesters in product development   code review phase
Testers in product development code review phase
Chetan Giridhar
 
Design patterns in python v0.1
Design patterns in python v0.1Design patterns in python v0.1
Design patterns in python v0.1
Chetan Giridhar
 
PyCon India 2011: Python Threads: Dive into GIL!
PyCon India 2011: Python Threads: Dive into GIL!PyCon India 2011: Python Threads: Dive into GIL!
PyCon India 2011: Python Threads: Dive into GIL!
Chetan Giridhar
 
Pycon11: Python threads: Dive into GIL!
Pycon11: Python threads: Dive into GIL!Pycon11: Python threads: Dive into GIL!
Pycon11: Python threads: Dive into GIL!
Chetan Giridhar
 

Recently uploaded (20)

How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 

Async programming and python

  • 1. Async Programming and Python PyCon India, 2014 Chetan Giridhar
  • 2. Basics • Programming tasks: o I/O bound o CPU bound • Say, you’re doing I/O o Will it complete immediately? When will it be done? o Wont they block you?
  • 3. Blocking I/O: Example import requests r = requests.get(‘http://google.co.in’) r.status_code • What if the request takes a long time? • Operation blocks until all the data is recieved from the server Can we do something in the meanwhile? Can we run another task, concurrently?
  • 4. Non Blocking / Async • Non-blocking means the ability to make continuous progress at all times • Resources needed for a response must not be monopolized • As such it can enable both lower latency, higher throughput
  • 5. Programming Models Synchronous model time time time Threaded model Asynchronous model Task 1 Task 2 Task 3
  • 6. Math • Task = make a call to http://ip.jsontest.com • Say, Task = Task1 = Task2 = Task 3 = 400ms • Sync Model o Time taken = Task1+ Task2 + Task3 = 1.2 sec • Threaded Model o Time taken = 510 ms • Async Model o Time taken = 460 ms What’s the magic here?
  • 7. Async Paradigm • Clients requests the event driven web server; • requests are processed by event loop; • event handlers cater to events with callbacks Client Event driven server I/O loop Event driven I/O loop Request IO loop handles request Event Handlers
  • 8. Reactor Pattern • Typical non blocking frameworks work on a philosophy of single threaded event loop o keeps polling for events Reactor Pattern Waiting for Events Handling Events
  • 9. More Details! • Framework typically maintains a list of file descriptors(fd), events to monitor and corresponding event handlers for each of the fd • Listening to events on a fd is a kernel space task o epoll, [kqueue/select] – libraries provide event notifications in a non-blocking way • Epoll watches file descriptors (sockets) and returns needed (READ, WRITE & ERROR) events
  • 10. Async way • Async strategy aims for: o Making I/O tasks non blocking o I/O tasks would run independently o generate an event when tasks are complete o with help of callbacks • Benefits o No need to wait till blocking I/O tasks are complete o More responsive real time applications o Thread safety isn't an issue • Can we solve any other Python problems with this mechanism? o Eliminating GIL?
  • 11. Async in Python • Frameworks o Tornado o Twisted o Gevent • Modules o Tulip o Asyncio
  • 12. Async in Python • Frameworks o Tornado o Twisted o Gevent • Modules o Tulip o Asyncio
  • 13. Asyncio • Part of Python library o The latest module for async application development • Only for Python > 3.4 o Incompatible with prior versions • A whole new way to development o Let’s you write self contained, synchronous looking tasks o Run two infinite loops at the same time on the same thread • Works with other framework o Tornado, Twisted, GEvent
  • 14. Asyncio… • Write single threaded concurrent code • Principle of Interleaved execution of subroutines • Co-operative scheduling o Only one task at a time • Based on libevent o Select, kpoll, kqueue
  • 15. Asyncio: Components Event loop Co-routines, Futures, Tasks Transports, Protocols
  • 16. Asyncio: Components • Event loop o Register, executing and cancelling calls o Schedule execution of a task (co-routine) o Creates transport (async client and server) o Runs I/O callbacks (Watches file descriptors) o Thread interface o [BaseEventLoop.create_task()] or async() o [asyncio.get_event_loop()]
  • 17. Asyncio: Components • Co-routine o Generator (“yield from”) o suspended at preset execution points, and o resumed later by keeping track of local state o @coroutine decorator
  • 18. Asyncio: Components • Task o responsible for executing a coroutine o If coroutine yields from a future, the task suspends the execution of the coroutine and waits for the future o coroutine restarts when future is done o Subclass of class Future o [async(coroutine)] o BaseEventLoop.create_task(coro)
  • 19. Asyncio: Components • Future o A class o for results that are available later import asyncio @asyncio.coroutine def slow_operation(future): yield from asyncio.sleep(1) <- Co-routine suspend future.set_result('Future is done!') def got_result(future): print(future.result()) loop.stop() loop = asyncio.get_event_loop() <- Event loop future = asyncio.Future() <- Future object asyncio.async(slow_operation(future)) <- Task future.add_done_callback(got_result) try: loop.run_forever() finally: loop.close()
  • 20. Asyncio: Components • transport o represent connections such as sockets, SSL connection and pipes o Async socket operations • Usually frameworks implement e.g. Tornado • protocols o represent applications such as HTTP client/server, SMTP, and FTP o Async http operation o [loop.create_connection()]
  • 21. Example: Asyncio Redis import asyncio import asyncio_redis @asyncio.coroutine def my_subscriber(channels): connection = yield from asyncio_redis.Connection.create(host='localhost', port=6379) subscriber = yield from connection.start_subscribe() yield from subscriber.subscribe(channels) while True: reply = yield from subscriber.next_published() print('Received: ', repr(reply.value), 'on channel', reply.channel) loop = asyncio.get_event_loop() asyncio.async(my_subscriber('channel-1')) asyncio.async(my_subscriber('channel-2')) loop.run_forever()
  • 22. Example: Asyncio ‘Tasks’ import asyncio @asyncio.coroutine def factorial(name, number): f = 1 for i in range(2, number+1): print("Task %s: Compute factorial(%s)..." % (name, i)) yield from asyncio.sleep(1) f *= i print("Task %s: factorial(%s) = %s" % (name, number, f)) loop = asyncio.get_event_loop() tasks = [ asyncio.async(factorial("A", 2)), asyncio.async(factorial("B", 3)), asyncio.async(factorial("C", 4))] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
  • 23. Async in Python • Frameworks o Tornado o Twisted o Gevent • Modules o Tulip o Asyncio
  • 24. Tornado Async • Event Loop => tornado.ioloop • Coroutine => tornado.gen.coroutine • Future => tornado.concurrent.future • Transport/Protocol => tornado.iostream • Bridge the gap => tornado.platform.asyncio – Combines asyncio and tornado in same event loop
  • 25. Tornado Async Http import tornado.ioloop from tornado.httpclient import AsyncHTTPClient def handle_request(response): '''callback needed when a response arrive''' if response.error: print("Error:", response.error) else: print(’Success') print(response.body) Before Event Loop Starts! Success b'{"ip": "117.192.252.80"}n' Callback http_client = AsyncHTTPClient() # initialize http client http_client.fetch(” http://ip.jsontest.com/", handle_request) print("Before Event Loop Starts!") tornado.ioloop.IOLoop.instance().start() # start the tornado ioloop
  • 26. Tornado Coroutine import tornado.web import tornado.gen from tornado.httpclient import AsyncHTTPClient class GenAsyncHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http_client = AsyncHTTPClient() response = yield http_client.fetch("http://google.com") print(response) application = tornado.web.Application([ (r"/", GenAsyncHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() gen.coroutine schedules the generator to be resumed when the Future is resolved ‘yield’ makes the function a generator The generator in turn returns a Future instance In this case, response, will resolve with response from fetch or an exception
  • 27. Tornado Engine class MainHandlerAsync(tornado.web.RequestHandler): @tornado.web.asynchronous @tornado.gen.engine def get(self): req = tornado.httpclient.HTTPRequest("http://127.0.0.1:8888/",) client = tornado.httpclient.AsyncHTTPClient() response = yield tornado.gen.Task(client.fetch, req) self.finish() application = tornado.web.Application([ (r"/async", MainHandlerAsync), ]) if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) tornado.ioloop.IOLoop.instance().start()
  • 28. Let’s create our Future! myfuture.py server.py import time import datetime from tornado.concurrent import return_future class AsyncHTTPClient(object): @return_future def fetch(self, url, callback=None): print("In my fetch") time.sleep(0.02) result = str(datetime.datetime.utcnow()) callback(result) import tornado.web import tornado.gen from myfuture import AsyncHTTPClient def test(arg): print('In test:' + arg) class GenAsync(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http_client = AsyncHTTPClient() r = yield http_client.fetch(“http://google.com”,test) print(r) application = tornado.web.Application([ (r"/", GenAsync),]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
  • 30. Work to be achieved
  • 31. Performance Results ab -n 500 -c 10 http://localhost:8888/blocking ab -n 500 -c 10 http://localhost:8888/async 6000 5000 4000 3000 2000 1000 0 Time per request Async Blocking Async Blocking 200 150 100 50 0 Requests per second Async Blocking Async Blocking
  • 32. Learnings • Async programming is an efficient, easy to understand design and code • Python asyncio module is comprehensive • Has generic use cases for vast variety of applications o Responsive web applications o Networking applications • Requires a new way to program and design
  • 33. Recommendations • Async programming is not a holistic solution • It has its own pros and cons o Suitable for primarily I/O bound applications o Needs enough tasks available to run • asyncio module is only available for Python 3 applications • Also explore other methods of concurrency: o Eventlets o STM o Multiprocessing/threads o Special languages e.g. GO, Scala • Understand and use 
  • 34. References • asyncio – http://python.org • Python asyncio – o http://www.buzzcapture.com o www.slideshare.net/saghul • Tornado – http://tornadoweb.org • Multithreading – www.drdobbs.com • Event loop: https://docs.python.org/3/library/asyncio-eventloop. html
  • 35. Contact Us • Chetan Giridhar o www.technobeans.com o https://github.com/cjgiridhar • Vishal Kanaujia o www.freethreads.wordpress.com o https://github.com/vishalkanaujia
  • 37. Asyncio: example import asyncio @asyncio.coroutine def create(): yield from asyncio.sleep(3.0) print("(1) create file") @asyncio.coroutine def write(): yield from asyncio.sleep(1.0) print("(2) write into file") @asyncio.coroutine def close(): print("(3) close file") @asyncio.coroutine def test(): asyncio.async(create()) asyncio.async(write()) asyncio.async(close()) yield from asyncio.sleep(2.0) loop.stop() loop = asyncio.get_event_loop() asyncio.async(test()) loop.run_forever() print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop)) loop.close()
  • 38. Python Async Modules • Asynccore • Asyncchat • Gevent • Twisted • Eventlets
  • 39. Concurrency Techniques • Multithreading/processing • Green Threads • STM
  • 40. Tornado + AsyncIO from tornado.platform.asyncio import AsyncIOMainLoop from tornado.httpclient import AsyncHTTPClient import asyncio AsyncIOMainLoop().install() -- # Tell Tornado to use the asyncio eventloop loop = asyncio.get_event_loop() -- # get the loop http_client = AsyncHTTPClient() -- # the Tornado HTTP client def aio_fetch(client, url, **kwargs): fut = asyncio.Future() client.fetch(url, callback=fut.set_result, **kwargs) return fut @asyncio.coroutine def main(): print("fetching my site") mysite = yield from aio_fetch(http_client, "http://google.com/") print("hello httpbin") httpbin = yield from aio_fetch(http_client, "http://httpbin.org?q=%d" % mysite.code) print(httpbin.body) loop.run_until_complete(main())
  • 41. Co-routine v/s Callback import asyncio def just_print_messages(loop): print('Just print') loop.call_later(1, just_print_messages, loop) def main(): loop = asyncio.get_event_loop() try: loop.call_soon(just_print_messages, loop) loop.run_forever() finally: loop.close() if __name__ == '__main__': main() import asyncio @asyncio.coroutine def just_print_messages(): while True: print('Just print') yield from asyncio.sleep(1) def main(): loop = asyncio.get_event_loop() try: loop.run_until_complete(just_print_messages()) finally: loop.close() if __name__ == '__main__': main()
  • 42. Async in NodeJS request is an var http = require(‘http’); event var server = http.createServer; server.on(‘request’, function(request,response) { response.writeHead(200); response.end(‘Hello World’); }).listen(8001); Callback console.log(‘Server running on port 8001’);

Editor's Notes

  • #15: Event loops use cooperative scheduling: an event loop only runs one task at a time. Other tasks may run in parallel if other event loops are running in different threads. While a task waits for the completion of a future, the event loop executes a new task.
  • #17: Event loop : Central execution device BaseEventLoop.add_reader(fd, callback, *args) Start watching the file descriptor for read availability and then call the callback with specified arguments. BaseEventLoop.remove_reader(fd) Stop watching the file descriptor for read availability. BaseEventLoop.add_writer(fd, callback, *args) Start watching the file descriptor for write availability and then call the callback with specified arguments. BaseEventLoop.remove_writer(fd) Stop watching the file descriptor for write availability.
  • #20: Add an example
  • #21: A Transport represents a connection – e.g. a socket, pipe, or SSL connection • typically implemented by the framework • A Protocol represents an application – e.g. an HTTP server or client • typically implemented by you!