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)
Ad

More Related Content

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
Damien Cassou
 
Rust
RustRust
Rust
Chih-Hsuan Kuo
 
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
RameshNair6
 
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
Andrew Svetlov
 
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
it-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é
 
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
 
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
RameshNair6
 
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
 
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
 
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
it-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
 

Viewers also liked (11)

如何提高研发效率
如何提高研发效率如何提高研发效率
如何提高研发效率
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
 
如何提高研发效率
如何提高研发效率如何提高研发效率
如何提高研发效率
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
 
Ad

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
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 — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
it-people
 
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
 
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
 
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 — быть или не быть?» Александр Мокров, 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
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗
Pofat Tseng
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
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
 
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
 
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
 
Ad

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
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
 
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
 

Recently uploaded (20)

Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 

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

  • 1. Tikitu de Jager • @tTikitu • [email protected] 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)