SlideShare a Scribd company logo
Tikitu de Jager • @tTikitu • tikitu@buzzcapture.com
going async
coroutines
event loops
non-blocking I/O
PUN • Utrecht • 20-6-2014
magic
import asyncio
import asyncio_redis
!
@asyncio.coroutine
def my_subscriber(channel):
# Create connection
connection = yield from asyncio_redis.Connection.create(host='localhost',
port=6379)
# Create subscriber.
subscriber = yield from connection.start_subscribe()
# Subscribe to channel.
yield from subscriber.subscribe([channel])
# Wait for incoming events.
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()
source: asyncio-redis
non-blocking I/O
queueing for coffee
starbucks
just waiting around
coffee as metaphor for I/O
❖ blocking I/O is queueing for coffee
❖ guy in front wants 17 litres of kopi luwak
❖ all I want is an espresso
❖ non-blocking I/O is the starbucks model
❖ give your order, then go wait somewhere
❖ they call you back when it’s ready
“non-blocking”?
starbucks queueing is not useful if your application is
❖ CPU-bound
❖ I/O-bound by pushing bits
it is useful if you spend most of your time waiting
doing stuff still takes time
waiting
most I/O is not pushing bits:
❖ server waits for connections
❖ call a service: wait for response
❖ wait for socket buffer to fill
if you’re just waiting: yield the CPU
… but then who will give it back to you? …
event loop
did anything happen?
how about now?
callback hell
you know this
❖ GUI programming: “when this button is clicked…”
❖ (old-fashioned) javascript onclick &c
❖ event loop checks for events and runs callbacks
❖ (select module makes polling for events easy)
callbacks for non-blocking I/O?
a_socket.recv(bufsize=16)
event_loop.when_socket_has_ready_buffer(a_s, 16, callback_f)
“callback hell”
coroutines
stop/go
generators
yield
coroutines and generators
a coroutine is a routine (function) that can pause
and resume its execution
def a_coroutine():
do_some_stuff()
yield
do_some_more_stuff()
def a_coroutine():
do_some_stuff()
yield to some_other_coroutine # invented syntax
do_some_more_stuff()
A generator is a coroutine
that can only yield to its caller
yield to the event loop
import asyncio
import asyncio_redis
!
@asyncio.coroutine
def my_subscriber(channels):
# [snip]
# Wait for incoming events.
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()
roll-your-own event loop
def loop():
while True:
for coroutine in waiting_list:
if io_is_ready_for(coroutine):
running_list.push(coroutine)
coroutine = running_list.pop()
coroutine.next()
(p.s. don’t do this)
what’ll it be?
twisted
gevent
asyncio
node.js
twisted
❖ networking protocols
❖ callbacks (methods on a “protocol” class)
❖ e.g. connectionMade(self), dataReceived(self, data)
❖ “you don't port an application to Twisted: You write a
Twisted application in most cases.” —Jesse Noller
❖ “deferred”: abstraction now usually called Future or
Promise (proxy for a value that will be computed later)
asyncio
❖ similar high-level protocols but also
❖ intends to provide a base layer for other libraries
❖ yield from
❖ python3 stdlib
❖ (how I got interested in this whole business)
yield from
event_loop.please_run_for_me(a_generator())
!
def a_generator():
for val in nested_generator():
yield val
!
def nested_generator():
for val in deeper_nested_generator():
yield val
!
def deeper_nested_generator():
event_loop.register(self, for_io_op='recv', on_socket=a_socket)
yield
return a_socket.recv()
… but what if we have to support generator send()?
def a_function():
nested_function()
def nested_function():
deeper_nested_function()
def deeper_nested_function():
return a_socket.recv()
send() the wrong way
gen = a_generator()
gen.next()
gen.send(1)
gen.send(2)
gen.next()
!
def a_generator():
gen = nested_generator()
to_yield = gen.next()
while True:
to_send = yield to_yield
if to_send is None:
to_yield = gen.next()
else:
to_yield = gen.send(to_send)
D
anger! Untested
probably incorrect code!
next() send() throw() close()
_i = iter(EXPR)
try:
_y = next(_i)
except StopIteration as _e:
_r = _e.value
else:
while 1:
try:
_s = yield _y
except GeneratorExit as _e:
try:
_m = _i.close
except AttributeError:
pass
else:
_m()
raise _e
except BaseException as _e:
_x = sys.exc_info()
try:
_m = _i.throw
except AttributeError:
raise _e
else:
try:
_y = _m(*_x)
except StopIteration as _e:
_r = _e.value
break
else:
try:
if _s is None:
_y = next(_i)
else:
_y = _i.send(_s)
except StopIteration as _e:
_r = _e.value
break
RESULT = _r
RESULT = yield from EXPR
def a_generator():
yield from nested_generator()
def nested_generator():
yield from deeper_nested_generator()
def deeper_nested_generator():
event_loop.register(self, for_io_op='recv',
on_socket=a_socket)
yield
return a_socket.recv()
asyncio
❖ yield from
❖ its own low-level I/O operations (socket recv &c.)
❖ futures, promises, timers, …
❖ networking protocols
gevent
def a_generator():
yield from nested_generator()
def nested_generator():
yield from deeper_nested_generator()
def deeper_nested_generator():
event_loop.register(self, for_io_op='recv',
on_socket=a_socket)
yield
return a_socket.recv()
from gevent import monkey; monkey.patch_all()
!
def a_function():
nested_function()
def nested_function():
deeper_nested_function()
def deeper_nested_function():
return a_socket.recv() # monkey-patched!
!
import gevent
jobs = [gevent.spawn(a_function) for _ in range(5)]
gevent.wait(jobs)
how?!
greenlets
❖ full coroutines
❖ monkey-patched primitives can “yield to” the event loop
directly
❖ C extension for CPython
node.js
really?
the summaries
modules
tech
buzzwords
module summary
twisted
❖ venerable
❖ focus on networking protocols
❖ perceived as large and complex; porting not easy
gevent
❖ near “drop-in” in synchronous code
❖ python 3 support is … coming?
asyncio
❖ python 3 stdlib
❖ (“Tulip” is a python 2 port: “yield From(a_generator)”)
❖ aims to be both low-level and protocol-level library
tech summary
greenlets
❖ full coroutines
❖ CPython hack; some pypy support
yield from
❖ python 3
❖ nested generators
❖ goldilocks solution?
callbacks
❖ low-tech, no special support needed
❖ promises, futures, etc: there is space for useful abstraction
❖ node.js
buzzwords
❖ non-blocking I/O: yield the CPU instead of waiting
❖ an event loop gives it back to you when what you’re
waiting for happens
❖ coroutines and generators let you write synchronous-
style functions and still yield to the event loop mid-way
that’s all folks
and yes
we’re
hiring
thank you’s and references
❖ y’all for your attention
❖ @saghul for getting me started on this whole business
❖ Peter Portante for a 2011 PyCon talk on coroutines
❖ Reinout & Maurits for PyGrunn summaries
❖ PEPs:
❖ 3156 (asyncio)
❖ 380 (yield from)

More Related Content

What's hot

Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
Damien Cassou
 
Rust
RustRust
Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio
Saúl Ibarra Corretgé
 
Don't do this
Don't do thisDon't do this
Don't do this
Richard Jones
 
LvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncioLvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncio
Roman Rader
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
Ramesh Nair
 
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Péhápkaři
 
Of Harmony and Stinginess: Applicative, Monad, and iterative library design
Of Harmony and Stinginess: Applicative, Monad, and iterative library designOf Harmony and Stinginess: Applicative, Monad, and iterative library design
Of Harmony and Stinginess: Applicative, Monad, and iterative library design
jspha
 
node ffi
node ffinode ffi
node ffi
偉格 高
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
Cory Forsyth
 
Perl: Coro asynchronous
Perl: Coro asynchronous Perl: Coro asynchronous
Perl: Coro asynchronous
Shmuel Fomberg
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
Shmuel Fomberg
 
Asyncio
AsyncioAsyncio
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014it-people
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
DEVTYPE
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
Stefan
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp way
Giordano Scalzo
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
Mohammad Shaker
 
Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
Saúl Ibarra Corretgé
 

What's hot (20)

Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
 
Rust
RustRust
Rust
 
Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio
 
Don't do this
Don't do thisDon't do this
Don't do this
 
LvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncioLvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncio
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
 
Of Harmony and Stinginess: Applicative, Monad, and iterative library design
Of Harmony and Stinginess: Applicative, Monad, and iterative library designOf Harmony and Stinginess: Applicative, Monad, and iterative library design
Of Harmony and Stinginess: Applicative, Monad, and iterative library design
 
node ffi
node ffinode ffi
node ffi
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Perl: Coro asynchronous
Perl: Coro asynchronous Perl: Coro asynchronous
Perl: Coro asynchronous
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
Asyncio
AsyncioAsyncio
Asyncio
 
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp way
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
 

Viewers also liked

如何提高研发效率
如何提高研发效率如何提高研发效率
如何提高研发效率
Leo Zhou
 
Qml 培訓課程 multi media
Qml 培訓課程   multi mediaQml 培訓課程   multi media
Qml 培訓課程 multi media
diro fan
 
Protocol libraries the right way
Protocol libraries the right wayProtocol libraries the right way
Protocol libraries the right way
Leo Zhou
 
Elastic HBase on Mesos - HBaseCon 2015
Elastic HBase on Mesos - HBaseCon 2015Elastic HBase on Mesos - HBaseCon 2015
Elastic HBase on Mesos - HBaseCon 2015
Cosmin Lehene
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
Ganesh Kondal
 
Tokyo HBase Meetup - Realtime Big Data at Facebook with Hadoop and HBase (ja)
Tokyo HBase Meetup - Realtime Big Data at Facebook with Hadoop and HBase (ja)Tokyo HBase Meetup - Realtime Big Data at Facebook with Hadoop and HBase (ja)
Tokyo HBase Meetup - Realtime Big Data at Facebook with Hadoop and HBase (ja)
tatsuya6502
 
HBase for Architects
HBase for ArchitectsHBase for Architects
HBase for Architects
Nick Dimiduk
 
HBase Vs Cassandra Vs MongoDB - Choosing the right NoSQL database
HBase Vs Cassandra Vs MongoDB - Choosing the right NoSQL databaseHBase Vs Cassandra Vs MongoDB - Choosing the right NoSQL database
HBase Vs Cassandra Vs MongoDB - Choosing the right NoSQL database
Edureka!
 
Apache HBase Performance Tuning
Apache HBase Performance TuningApache HBase Performance Tuning
Apache HBase Performance Tuning
Lars Hofhansl
 
Node.js and The Internet of Things
Node.js and The Internet of ThingsNode.js and The Internet of Things
Node.js and The Internet of Things
Losant
 
Montreal Girl Geeks: Building the Modern Web
Montreal Girl Geeks: Building the Modern WebMontreal Girl Geeks: Building the Modern Web
Montreal Girl Geeks: Building the Modern Web
Rachel Andrew
 

Viewers also liked (11)

如何提高研发效率
如何提高研发效率如何提高研发效率
如何提高研发效率
 
Qml 培訓課程 multi media
Qml 培訓課程   multi mediaQml 培訓課程   multi media
Qml 培訓課程 multi media
 
Protocol libraries the right way
Protocol libraries the right wayProtocol libraries the right way
Protocol libraries the right way
 
Elastic HBase on Mesos - HBaseCon 2015
Elastic HBase on Mesos - HBaseCon 2015Elastic HBase on Mesos - HBaseCon 2015
Elastic HBase on Mesos - HBaseCon 2015
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Tokyo HBase Meetup - Realtime Big Data at Facebook with Hadoop and HBase (ja)
Tokyo HBase Meetup - Realtime Big Data at Facebook with Hadoop and HBase (ja)Tokyo HBase Meetup - Realtime Big Data at Facebook with Hadoop and HBase (ja)
Tokyo HBase Meetup - Realtime Big Data at Facebook with Hadoop and HBase (ja)
 
HBase for Architects
HBase for ArchitectsHBase for Architects
HBase for Architects
 
HBase Vs Cassandra Vs MongoDB - Choosing the right NoSQL database
HBase Vs Cassandra Vs MongoDB - Choosing the right NoSQL databaseHBase Vs Cassandra Vs MongoDB - Choosing the right NoSQL database
HBase Vs Cassandra Vs MongoDB - Choosing the right NoSQL database
 
Apache HBase Performance Tuning
Apache HBase Performance TuningApache HBase Performance Tuning
Apache HBase Performance Tuning
 
Node.js and The Internet of Things
Node.js and The Internet of ThingsNode.js and The Internet of Things
Node.js and The Internet of Things
 
Montreal Girl Geeks: Building the Modern Web
Montreal Girl Geeks: Building the Modern WebMontreal Girl Geeks: Building the Modern Web
Montreal Girl Geeks: Building the Modern Web
 

Similar to Python meetup: coroutines, event loops, and non-blocking I/O

The journey of asyncio adoption in instagram
The journey of asyncio adoption in instagramThe journey of asyncio adoption in instagram
The journey of asyncio adoption in instagram
Jimmy Lai
 
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
Yothin Muangsommuk
 
Gevent be or not to be
Gevent be or not to beGevent be or not to be
Gevent be or not to be
Aleksandr Mokrov
 
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
it-people
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
Guido Pio Mariotti
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗
Pofat Tseng
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
Tomasz Kowalczewski
 
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
ThierryAbalea
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
Andrey Breslav
 
Introducing to Asynchronous Programming
Introducing to Asynchronous  ProgrammingIntroducing to Asynchronous  Programming
Introducing to Asynchronous Programming
Александр Федоров
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Michael Barker
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael Barker
JAX London
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
Saúl Ibarra Corretgé
 
Meetup talk: Readying your Go Webservice
Meetup talk: Readying your Go WebserviceMeetup talk: Readying your Go Webservice
Meetup talk: Readying your Go Webservice
Ralph Ligtenberg
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
libuv, NodeJS and everything in between
libuv, NodeJS and everything in betweenlibuv, NodeJS and everything in between
libuv, NodeJS and everything in between
Saúl Ibarra Corretgé
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 

Similar to Python meetup: coroutines, event loops, and non-blocking I/O (20)

The journey of asyncio adoption in instagram
The journey of asyncio adoption in instagramThe journey of asyncio adoption in instagram
The journey of asyncio adoption in instagram
 
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
 
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
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
Introducing to Asynchronous Programming
Introducing to Asynchronous  ProgrammingIntroducing to Asynchronous  Programming
Introducing to Asynchronous Programming
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael Barker
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Meetup talk: Readying your Go Webservice
Meetup talk: Readying your Go WebserviceMeetup talk: Readying your Go Webservice
Meetup talk: Readying your Go Webservice
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
libuv, NodeJS and everything in between
libuv, NodeJS and everything in betweenlibuv, NodeJS and everything in between
libuv, NodeJS and everything in between
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 

More from Buzzcapture

Presentatie Online Tuesday Buzzcapture 10 mei 2016
Presentatie Online Tuesday Buzzcapture 10 mei 2016Presentatie Online Tuesday Buzzcapture 10 mei 2016
Presentatie Online Tuesday Buzzcapture 10 mei 2016
Buzzcapture
 
Gastcollege Hogeschool Arnhem en Nijmegen
Gastcollege Hogeschool Arnhem en NijmegenGastcollege Hogeschool Arnhem en Nijmegen
Gastcollege Hogeschool Arnhem en Nijmegen
Buzzcapture
 
Presentatie Buzzcapture Social Media Club Utrecht #SMC030
Presentatie Buzzcapture Social Media Club Utrecht #SMC030Presentatie Buzzcapture Social Media Club Utrecht #SMC030
Presentatie Buzzcapture Social Media Club Utrecht #SMC030
Buzzcapture
 
Freelunch verzorgd door Buzzcapture
Freelunch verzorgd door BuzzcaptureFreelunch verzorgd door Buzzcapture
Freelunch verzorgd door Buzzcapture
Buzzcapture
 
Buzzcapture presentatie #SMC036 Almere
Buzzcapture presentatie #SMC036 AlmereBuzzcapture presentatie #SMC036 Almere
Buzzcapture presentatie #SMC036 Almere
Buzzcapture
 
Gemeentenindex 2015
Gemeentenindex 2015Gemeentenindex 2015
Gemeentenindex 2015
Buzzcapture
 
Tour de France 2015 on Twitter
Tour de France 2015 on TwitterTour de France 2015 on Twitter
Tour de France 2015 on Twitter
Buzzcapture
 
Presentatie Social Media & crisiscommunicatie
Presentatie Social Media & crisiscommunicatiePresentatie Social Media & crisiscommunicatie
Presentatie Social Media & crisiscommunicatie
Buzzcapture
 
Presentatie Buzzcapture #Pumadag 2015
Presentatie Buzzcapture #Pumadag 2015Presentatie Buzzcapture #Pumadag 2015
Presentatie Buzzcapture #Pumadag 2015
Buzzcapture
 
12 redenen om een Facebook evenement aan te maken
12 redenen om een Facebook evenement aan te maken12 redenen om een Facebook evenement aan te maken
12 redenen om een Facebook evenement aan te maken
Buzzcapture
 
Handleiding: Hoe maak je een Facebook evenement aan?
Handleiding: Hoe maak je een Facebook evenement aan?Handleiding: Hoe maak je een Facebook evenement aan?
Handleiding: Hoe maak je een Facebook evenement aan?
Buzzcapture
 
Presentatie Buzz15 Jaap van Zessen
Presentatie Buzz15 Jaap van ZessenPresentatie Buzz15 Jaap van Zessen
Presentatie Buzz15 Jaap van Zessen
Buzzcapture
 
Presentatie #Buzz15 ANP en Buzzcapture
Presentatie #Buzz15 ANP en BuzzcapturePresentatie #Buzz15 ANP en Buzzcapture
Presentatie #Buzz15 ANP en Buzzcapture
Buzzcapture
 
Presentatie Buzzcapture SMC055 Apeldoorn
Presentatie Buzzcapture SMC055 ApeldoornPresentatie Buzzcapture SMC055 Apeldoorn
Presentatie Buzzcapture SMC055 Apeldoorn
Buzzcapture
 
Buzzcapture Contentkalender 2015
Buzzcapture Contentkalender 2015Buzzcapture Contentkalender 2015
Buzzcapture Contentkalender 2015
Buzzcapture
 
Presentatie Buzzcapture Utrecht Data School #4
Presentatie Buzzcapture Utrecht Data School #4Presentatie Buzzcapture Utrecht Data School #4
Presentatie Buzzcapture Utrecht Data School #4
Buzzcapture
 
Presentatie Buzzcapture bij HSMAI 23 september
Presentatie Buzzcapture bij HSMAI 23 septemberPresentatie Buzzcapture bij HSMAI 23 september
Presentatie Buzzcapture bij HSMAI 23 september
Buzzcapture
 
Presentatie Alex van Leeuwen (Buzzcapture) tijdens #Buzz14
Presentatie Alex van Leeuwen (Buzzcapture) tijdens #Buzz14Presentatie Alex van Leeuwen (Buzzcapture) tijdens #Buzz14
Presentatie Alex van Leeuwen (Buzzcapture) tijdens #Buzz14
Buzzcapture
 
Presentatie Robin Wollenberg (BAM) tijdens #Buzz14
Presentatie Robin Wollenberg (BAM) tijdens #Buzz14Presentatie Robin Wollenberg (BAM) tijdens #Buzz14
Presentatie Robin Wollenberg (BAM) tijdens #Buzz14
Buzzcapture
 
Aflevering 5 Wie is de Mol Social Media Analyse #WIDM
Aflevering 5 Wie is de Mol Social Media Analyse #WIDMAflevering 5 Wie is de Mol Social Media Analyse #WIDM
Aflevering 5 Wie is de Mol Social Media Analyse #WIDM
Buzzcapture
 

More from Buzzcapture (20)

Presentatie Online Tuesday Buzzcapture 10 mei 2016
Presentatie Online Tuesday Buzzcapture 10 mei 2016Presentatie Online Tuesday Buzzcapture 10 mei 2016
Presentatie Online Tuesday Buzzcapture 10 mei 2016
 
Gastcollege Hogeschool Arnhem en Nijmegen
Gastcollege Hogeschool Arnhem en NijmegenGastcollege Hogeschool Arnhem en Nijmegen
Gastcollege Hogeschool Arnhem en Nijmegen
 
Presentatie Buzzcapture Social Media Club Utrecht #SMC030
Presentatie Buzzcapture Social Media Club Utrecht #SMC030Presentatie Buzzcapture Social Media Club Utrecht #SMC030
Presentatie Buzzcapture Social Media Club Utrecht #SMC030
 
Freelunch verzorgd door Buzzcapture
Freelunch verzorgd door BuzzcaptureFreelunch verzorgd door Buzzcapture
Freelunch verzorgd door Buzzcapture
 
Buzzcapture presentatie #SMC036 Almere
Buzzcapture presentatie #SMC036 AlmereBuzzcapture presentatie #SMC036 Almere
Buzzcapture presentatie #SMC036 Almere
 
Gemeentenindex 2015
Gemeentenindex 2015Gemeentenindex 2015
Gemeentenindex 2015
 
Tour de France 2015 on Twitter
Tour de France 2015 on TwitterTour de France 2015 on Twitter
Tour de France 2015 on Twitter
 
Presentatie Social Media & crisiscommunicatie
Presentatie Social Media & crisiscommunicatiePresentatie Social Media & crisiscommunicatie
Presentatie Social Media & crisiscommunicatie
 
Presentatie Buzzcapture #Pumadag 2015
Presentatie Buzzcapture #Pumadag 2015Presentatie Buzzcapture #Pumadag 2015
Presentatie Buzzcapture #Pumadag 2015
 
12 redenen om een Facebook evenement aan te maken
12 redenen om een Facebook evenement aan te maken12 redenen om een Facebook evenement aan te maken
12 redenen om een Facebook evenement aan te maken
 
Handleiding: Hoe maak je een Facebook evenement aan?
Handleiding: Hoe maak je een Facebook evenement aan?Handleiding: Hoe maak je een Facebook evenement aan?
Handleiding: Hoe maak je een Facebook evenement aan?
 
Presentatie Buzz15 Jaap van Zessen
Presentatie Buzz15 Jaap van ZessenPresentatie Buzz15 Jaap van Zessen
Presentatie Buzz15 Jaap van Zessen
 
Presentatie #Buzz15 ANP en Buzzcapture
Presentatie #Buzz15 ANP en BuzzcapturePresentatie #Buzz15 ANP en Buzzcapture
Presentatie #Buzz15 ANP en Buzzcapture
 
Presentatie Buzzcapture SMC055 Apeldoorn
Presentatie Buzzcapture SMC055 ApeldoornPresentatie Buzzcapture SMC055 Apeldoorn
Presentatie Buzzcapture SMC055 Apeldoorn
 
Buzzcapture Contentkalender 2015
Buzzcapture Contentkalender 2015Buzzcapture Contentkalender 2015
Buzzcapture Contentkalender 2015
 
Presentatie Buzzcapture Utrecht Data School #4
Presentatie Buzzcapture Utrecht Data School #4Presentatie Buzzcapture Utrecht Data School #4
Presentatie Buzzcapture Utrecht Data School #4
 
Presentatie Buzzcapture bij HSMAI 23 september
Presentatie Buzzcapture bij HSMAI 23 septemberPresentatie Buzzcapture bij HSMAI 23 september
Presentatie Buzzcapture bij HSMAI 23 september
 
Presentatie Alex van Leeuwen (Buzzcapture) tijdens #Buzz14
Presentatie Alex van Leeuwen (Buzzcapture) tijdens #Buzz14Presentatie Alex van Leeuwen (Buzzcapture) tijdens #Buzz14
Presentatie Alex van Leeuwen (Buzzcapture) tijdens #Buzz14
 
Presentatie Robin Wollenberg (BAM) tijdens #Buzz14
Presentatie Robin Wollenberg (BAM) tijdens #Buzz14Presentatie Robin Wollenberg (BAM) tijdens #Buzz14
Presentatie Robin Wollenberg (BAM) tijdens #Buzz14
 
Aflevering 5 Wie is de Mol Social Media Analyse #WIDM
Aflevering 5 Wie is de Mol Social Media Analyse #WIDMAflevering 5 Wie is de Mol Social Media Analyse #WIDM
Aflevering 5 Wie is de Mol Social Media Analyse #WIDM
 

Recently uploaded

14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 

Recently uploaded (20)

14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 

Python meetup: coroutines, event loops, and non-blocking I/O

  • 1. Tikitu de Jager • @tTikitu • tikitu@buzzcapture.com going async coroutines event loops non-blocking I/O PUN • Utrecht • 20-6-2014
  • 2. magic import asyncio import asyncio_redis ! @asyncio.coroutine def my_subscriber(channel): # Create connection connection = yield from asyncio_redis.Connection.create(host='localhost', port=6379) # Create subscriber. subscriber = yield from connection.start_subscribe() # Subscribe to channel. yield from subscriber.subscribe([channel]) # Wait for incoming events. 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() source: asyncio-redis
  • 3. non-blocking I/O queueing for coffee starbucks just waiting around
  • 4. coffee as metaphor for I/O ❖ blocking I/O is queueing for coffee ❖ guy in front wants 17 litres of kopi luwak ❖ all I want is an espresso ❖ non-blocking I/O is the starbucks model ❖ give your order, then go wait somewhere ❖ they call you back when it’s ready
  • 5. “non-blocking”? starbucks queueing is not useful if your application is ❖ CPU-bound ❖ I/O-bound by pushing bits it is useful if you spend most of your time waiting doing stuff still takes time
  • 6. waiting most I/O is not pushing bits: ❖ server waits for connections ❖ call a service: wait for response ❖ wait for socket buffer to fill if you’re just waiting: yield the CPU … but then who will give it back to you? …
  • 7. event loop did anything happen? how about now? callback hell
  • 8. you know this ❖ GUI programming: “when this button is clicked…” ❖ (old-fashioned) javascript onclick &c ❖ event loop checks for events and runs callbacks ❖ (select module makes polling for events easy)
  • 9. callbacks for non-blocking I/O? a_socket.recv(bufsize=16) event_loop.when_socket_has_ready_buffer(a_s, 16, callback_f) “callback hell”
  • 11. coroutines and generators a coroutine is a routine (function) that can pause and resume its execution def a_coroutine(): do_some_stuff() yield do_some_more_stuff() def a_coroutine(): do_some_stuff() yield to some_other_coroutine # invented syntax do_some_more_stuff() A generator is a coroutine that can only yield to its caller
  • 12. yield to the event loop import asyncio import asyncio_redis ! @asyncio.coroutine def my_subscriber(channels): # [snip] # Wait for incoming events. 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()
  • 13. roll-your-own event loop def loop(): while True: for coroutine in waiting_list: if io_is_ready_for(coroutine): running_list.push(coroutine) coroutine = running_list.pop() coroutine.next() (p.s. don’t do this)
  • 15. twisted ❖ networking protocols ❖ callbacks (methods on a “protocol” class) ❖ e.g. connectionMade(self), dataReceived(self, data) ❖ “you don't port an application to Twisted: You write a Twisted application in most cases.” —Jesse Noller ❖ “deferred”: abstraction now usually called Future or Promise (proxy for a value that will be computed later)
  • 16. asyncio ❖ similar high-level protocols but also ❖ intends to provide a base layer for other libraries ❖ yield from ❖ python3 stdlib ❖ (how I got interested in this whole business)
  • 17. yield from event_loop.please_run_for_me(a_generator()) ! def a_generator(): for val in nested_generator(): yield val ! def nested_generator(): for val in deeper_nested_generator(): yield val ! def deeper_nested_generator(): event_loop.register(self, for_io_op='recv', on_socket=a_socket) yield return a_socket.recv() … but what if we have to support generator send()? def a_function(): nested_function() def nested_function(): deeper_nested_function() def deeper_nested_function(): return a_socket.recv()
  • 18. send() the wrong way gen = a_generator() gen.next() gen.send(1) gen.send(2) gen.next() ! def a_generator(): gen = nested_generator() to_yield = gen.next() while True: to_send = yield to_yield if to_send is None: to_yield = gen.next() else: to_yield = gen.send(to_send) D anger! Untested probably incorrect code!
  • 19. next() send() throw() close() _i = iter(EXPR) try: _y = next(_i) except StopIteration as _e: _r = _e.value else: while 1: try: _s = yield _y except GeneratorExit as _e: try: _m = _i.close except AttributeError: pass else: _m() raise _e except BaseException as _e: _x = sys.exc_info() try: _m = _i.throw except AttributeError: raise _e else: try: _y = _m(*_x) except StopIteration as _e: _r = _e.value break else: try: if _s is None: _y = next(_i) else: _y = _i.send(_s) except StopIteration as _e: _r = _e.value break RESULT = _r RESULT = yield from EXPR def a_generator(): yield from nested_generator() def nested_generator(): yield from deeper_nested_generator() def deeper_nested_generator(): event_loop.register(self, for_io_op='recv', on_socket=a_socket) yield return a_socket.recv()
  • 20. asyncio ❖ yield from ❖ its own low-level I/O operations (socket recv &c.) ❖ futures, promises, timers, … ❖ networking protocols
  • 21. gevent def a_generator(): yield from nested_generator() def nested_generator(): yield from deeper_nested_generator() def deeper_nested_generator(): event_loop.register(self, for_io_op='recv', on_socket=a_socket) yield return a_socket.recv() from gevent import monkey; monkey.patch_all() ! def a_function(): nested_function() def nested_function(): deeper_nested_function() def deeper_nested_function(): return a_socket.recv() # monkey-patched! ! import gevent jobs = [gevent.spawn(a_function) for _ in range(5)] gevent.wait(jobs) how?!
  • 22. greenlets ❖ full coroutines ❖ monkey-patched primitives can “yield to” the event loop directly ❖ C extension for CPython
  • 25. module summary twisted ❖ venerable ❖ focus on networking protocols ❖ perceived as large and complex; porting not easy gevent ❖ near “drop-in” in synchronous code ❖ python 3 support is … coming? asyncio ❖ python 3 stdlib ❖ (“Tulip” is a python 2 port: “yield From(a_generator)”) ❖ aims to be both low-level and protocol-level library
  • 26. tech summary greenlets ❖ full coroutines ❖ CPython hack; some pypy support yield from ❖ python 3 ❖ nested generators ❖ goldilocks solution? callbacks ❖ low-tech, no special support needed ❖ promises, futures, etc: there is space for useful abstraction ❖ node.js
  • 27. buzzwords ❖ non-blocking I/O: yield the CPU instead of waiting ❖ an event loop gives it back to you when what you’re waiting for happens ❖ coroutines and generators let you write synchronous- style functions and still yield to the event loop mid-way
  • 28. that’s all folks and yes we’re hiring
  • 29. thank you’s and references ❖ y’all for your attention ❖ @saghul for getting me started on this whole business ❖ Peter Portante for a 2011 PyCon talk on coroutines ❖ Reinout & Maurits for PyGrunn summaries ❖ PEPs: ❖ 3156 (asyncio) ❖ 380 (yield from)