SlideShare a Scribd company logo
asyncio internals
Saúl Ibarra Corretgé
@saghul
PyGrunn 2014
Friday, May 9, 14
Intro
New asynchronous I/O framework for Python
PEP-3156
Python >= 3.3 (backport available: Trollius)
Uses new language features: yield from
Designed to interoperate with other frameworks
You went to Rodrigo’s talk earlier today, right?
Friday, May 9, 14
Friday, May 9, 14
Architecture
Event loop
Coroutines, Futures and Tasks
Transports, Protocols and Streams
I’ll cover these
Homework!
Friday, May 9, 14
Event Loop
Friday, May 9, 14
Calculate
poll time
Poll
Run
callbacks
Friday, May 9, 14
There is no abstraction for an “event”
It runs callbacks which are put in a queue
Callbacks can be scheduled due to i/o, time or user
desire
The event loop acts as an implicit scheduler
Friday, May 9, 14
Sim
plified
def call_soon(self, callback, *args):
handle = events.Handle(callback, args, self)
self._ready.append(handle)
return handle
Friday, May 9, 14
events.Handle is like a “callbak wrapper”
The ready queue is a deque
Once per loop iteration al handles in the ready queue
are executed
Friday, May 9, 14
def call_later(self, delay, callback, *args):
return self.call_at(self.time() + delay, callback, *args)
def call_at(self, when, callback, *args):
timer = events.TimerHandle(when, callback, args, self)
heapq.heappush(self._scheduled, timer)
return timer
Sim
plified
Friday, May 9, 14
Timers are stored in a heap (loop._scheduled)
TimerHandle subclasses Handle, but stores the time
when it’s due and has comparison methods for keeping
the heap sorted by due time
Friday, May 9, 14
ntodo = len(self._ready)
for i in range(ntodo):
handle = self._ready.popleft()
if not handle._cancelled:
handle._run()
handle = None # break cycles
Friday, May 9, 14
This is the single place where the ready queue is
iterated over
A thread-safe iteration method is used, since other
threads could modify the ready queue (see
call_soon_threadsafe)
If any handles are scheduled while the ready queue is
being processed, they will be run on the next loop
iteration
Friday, May 9, 14
Different polling mechanisms on Unix: select, poll, epoll,
kqueue, devpoll
Windows is a completely different beast
Different paradigms: readyness vs completion
APIs are provided for both
I/O handling
Friday, May 9, 14
I/O handling APIs
Readyness style
add_reader/add_writer
remove_reader/remove_writer
Completion style
sock_recv/sock_sendall
sock_connect/sock_accept
Friday, May 9, 14
import selectors
New module in Python 3.4
Consistent interface to Unix polling mechanisms
On Windows it uses select()
64 file descriptors default* limit - WEBSCALE!
IOCP is the way to go, but has a different API
Caveat emptor: doesn’t work for file i/o
Friday, May 9, 14
Sim
plified
def add_reader(self, fd, callback, *args):
handle = events.Handle(callback, args, self)
try:
key = self._selector.get_key(fd)
except KeyError:
self._selector.register(fd, selectors.EVENT_READ, (handle, None))
else:
mask, (reader, writer) = key.events, key.data
self._selector.modify(fd, mask | selectors.EVENT_READ, (handle, writer))
if reader is not None:
reader.cancel()
Friday, May 9, 14
The selector key stores the fd, events and user
provided arbitrary data
In this case the arbitrary data is the reader, writer
handle tuple
Only one reader and writer per fd are allowed
Friday, May 9, 14
1.Calculate timeout
2.Block for I/O
3.Process I/O events: schedule callbacks
4.Process timers: schedule callbacks
5.Run pending callbacks
Polling for I/O
Friday, May 9, 14
timeout = None
if self._ready:
timeout = 0
elif self._scheduled:
# Compute the desired timeout.
when = self._scheduled[0]._when
deadline = max(0, when - self.time())
if timeout is None:
timeout = deadline
else:
timeout = min(timeout, deadline)
event_list = self._selector.select(timeout)
self._process_events(event_list)
end_time = self.time()
while self._scheduled:
handle = self._scheduled[0]
if handle._when >= end_time:
break
handle = heapq.heappop(self._scheduled)
self._ready.append(handle)
# run all handles in the ready queue...
Sim
plified
Friday, May 9, 14
If timeout is None an infinite poll is performed
_process_events puts the read / write handles in the
ready queue, if applicable
Friday, May 9, 14
def call_soon_threadsafe(self, callback, *args):
handle = self._call_soon(callback, args)
self._write_to_self()
return handle
Sim
plified
Friday, May 9, 14
The event loop has the read end of a socketpair added
to the selector
When _write_to_self is called the loop will be “waken
up” from the select/poll/epoll_wait/kevent syscall
Friday, May 9, 14
Coroutines, Futures & Tasks
Friday, May 9, 14
Generator functions, can also receive values
Use the @asyncio.coroutine decorator
Does extra checks in debug mode
Serves as documentation
Chain them with yield from
Coroutines
Friday, May 9, 14
Not actually PEP-3148 (concurrent.futures)
API almost identical
Represent a value which is not there yet
yield from can be used to wait for it!
asyncio.wrap_future can be used to wrap a PEP-3148
Future into one of these
Futures
Friday, May 9, 14
f = Future()
Usually a future will be the result of a function
f.set_result / f.set_exception
Someone will set the result eventually
yield from f
Wait until the result arrives
add_done_callback / remove_done_callback
Callback based interface
Friday, May 9, 14
def set_result(self, result):
if self._state != _PENDING:
raise InvalidStateError('{}: {!r}'.format(self._state, self))
self._result = result
self._state = _FINISHED
self._schedule_callbacks()
def _schedule_callbacks(self):
callbacks = self._callbacks[:]
if not callbacks:
return
self._callbacks[:] = []
for callback in callbacks:
self._loop.call_soon(callback, self)
Friday, May 9, 14
After the result or exception is set all callbacks added
with Future.add_done_callback are called
Note how callbacks are scheduled in the event loop
using call_soon
Friday, May 9, 14
Sim
plified
def sock_connect(self, sock, address):
fut = futures.Future(loop=self)
self._sock_connect(fut, False, sock, address)
return fut
def _sock_connect(self, fut, registered, sock, address):
fd = sock.fileno()
if registered:
self.remove_writer(fd)
if fut.cancelled():
return
try:
if not registered:
sock.connect(address)
else:
err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
if err != 0:
raise OSError(err, 'Connect call failed %s' % (address,))
except (BlockingIOError, InterruptedError):
self.add_writer(fd, self._sock_connect, fut, True, sock, address)
except Exception as exc:
fut.set_exception(exc)
else:
fut.set_result(None)
Friday, May 9, 14
Not a coroutine, but we can wait on it using yield from
because it returns a Future
The Uncallback Pattern (TM)
Hey, look at those nice exceptions: BlockingIOError,
InterruptedError
Much nicer than checking if errno is
EWOULDBLOCK or EINTR
Friday, May 9, 14
def run_until_complete(self, future):
future = tasks.async(future, loop=self)
future.add_done_callback(_raise_stop_error)
self.run_forever()
future.remove_done_callback(_raise_stop_error)
if not future.done():
raise RuntimeError('Event loop stopped before Future completed.')
return future.result()
Friday, May 9, 14
Loop.run_forever will run the loop until Loop.stop is
called
_raise_stop_error is an implementation detail, it causes
an exception to bubble up and makes run_forever
return
Friday, May 9, 14
def __iter__(self):
if not self.done():
self._blocking = True
yield self # This tells Task to wait for completion.
assert self.done(), "yield from wasn't used with future"
return self.result() # May raise too.
Friday, May 9, 14
Returning a value from __iter__ is the same as raising
StopIteration(value)
The _blocking flag is used to check if yield future was
used intead of yield from future
Task has a way to wait on a Future if yielded to it, also
checks that yield from was used (_blocking flag)
Friday, May 9, 14
Friday, May 9, 14
Unit of concurrent asynchronous work
It’s actually a coroutine wrapped in a Future
Magic!
Schedules callbacks using loop.call_soon
Use asyncio.async to run a coroutine in a Task
Tasks
Friday, May 9, 14
import asyncio
@asyncio.coroutine
def f(n, x):
while True:
print(n)
yield from asyncio.sleep(x)
loop = asyncio.get_event_loop()
asyncio.async(f('f1', 0.5))
asyncio.async(f('f2', 1.5))
loop.run_forever()
Friday, May 9, 14
Both coroutines will run concurrently
asyncio.async returns a Task if a coroutine was passed,
or the unchanged value if a Future was passed
Go and check how asyncio.sleep is implemented, it’s
really simple!
Friday, May 9, 14
def __init__(self, coro, *, loop=None):
assert iscoroutine(coro), repr(coro) # Not a coroutine function!
super().__init__(loop=loop)
self._coro = iter(coro) # Use the iterator just in case.
self._fut_waiter = None
self._loop.call_soon(self._step)
Sim
plified
Friday, May 9, 14
Tasks are not run immediately, the actual work is done
by Task._step, which is scheduled with loop.call_soon
_fut_waiter is used to store a Future which this Task is
waiting for
Friday, May 9, 14
Sim
plified
def _step(self, value=None, exc=None):
assert not self.done(), '_step(): already done'
coro = self._coro
self._fut_waiter = None
try:
if exc is not None:
result = coro.throw(exc)
elif value is not None:
result = coro.send(value)
else:
result = next(coro)
except StopIteration as exc:
self.set_result(exc.value)
except Exception as exc:
self.set_exception(exc)
except BaseException as exc:
self.set_exception(exc)
raise
else:
if isinstance(result, futures.Future):
# Yielded Future must come from Future.__iter__().
if result._blocking:
result._blocking = False
result.add_done_callback(self._wakeup)
self._fut_waiter = result
else:
# error...
elif result is None:
# Bare yield relinquishes control for one event loop iteration.
self._loop.call_soon(self._step)
else:
# error...
Friday, May 9, 14
The Magic (TM)
The coroutine is stepped over until it finishes
Note the check of _blocking to verify yield vs yield from
usage
The _wakeup function will schedule _step with either a
result or an exception
At any point in time, either _step is scheduled or
_fut_waiter is not None
Friday, May 9, 14
There is a lot more in asyncio
Go read PEP-3156
Don’t be afraid of looking under the hood
Don’t rely on internals, they are implementation details
Join the mailing list, check the third party libraries!
raise SystemExit
“I hear and I forget. I see and I remember.
I do and I understand.” - Confucius
Friday, May 9, 14
Questions?
bettercallsaghul.com
@saghul
Friday, May 9, 14

More Related Content

What's hot

스프링 부트와 로깅
스프링 부트와 로깅스프링 부트와 로깅
스프링 부트와 로깅Keesun Baik
 
How to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor NettyHow to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor NettyVMware Tanzu
 
Linux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old SecretsLinux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old SecretsBrendan Gregg
 
Filesystem Comparison: NFS vs GFS2 vs OCFS2
Filesystem Comparison: NFS vs GFS2 vs OCFS2Filesystem Comparison: NFS vs GFS2 vs OCFS2
Filesystem Comparison: NFS vs GFS2 vs OCFS2Giuseppe Paterno'
 
Tools for Solving Performance Issues
Tools for Solving Performance IssuesTools for Solving Performance Issues
Tools for Solving Performance IssuesOdoo
 
Prometheus – a next-gen Monitoring System
Prometheus – a next-gen Monitoring SystemPrometheus – a next-gen Monitoring System
Prometheus – a next-gen Monitoring SystemFabian Reinartz
 
Linux Locking Mechanisms
Linux Locking MechanismsLinux Locking Mechanisms
Linux Locking MechanismsKernel TLV
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript EngineKris Mok
 
Postgresql database administration volume 1
Postgresql database administration volume 1Postgresql database administration volume 1
Postgresql database administration volume 1Federico Campoli
 
How We Reduced Performance Tuning Time by Orders of Magnitude with Database O...
How We Reduced Performance Tuning Time by Orders of Magnitude with Database O...How We Reduced Performance Tuning Time by Orders of Magnitude with Database O...
How We Reduced Performance Tuning Time by Orders of Magnitude with Database O...ScyllaDB
 
Profiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf ToolsProfiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf ToolsemBO_Conference
 
High Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando PatroniHigh Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando PatroniZalando Technology
 
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...Altinity Ltd
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to CeleryIdan Gazit
 
Fluentd Overview, Now and Then
Fluentd Overview, Now and ThenFluentd Overview, Now and Then
Fluentd Overview, Now and ThenSATOSHI TAGOMORI
 
[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅NAVER D2
 
Better than you think: Handling JSON data in ClickHouse
Better than you think: Handling JSON data in ClickHouseBetter than you think: Handling JSON data in ClickHouse
Better than you think: Handling JSON data in ClickHouseAltinity Ltd
 
Altinity Cluster Manager: ClickHouse Management for Kubernetes and Cloud
Altinity Cluster Manager: ClickHouse Management for Kubernetes and CloudAltinity Cluster Manager: ClickHouse Management for Kubernetes and Cloud
Altinity Cluster Manager: ClickHouse Management for Kubernetes and CloudAltinity Ltd
 

What's hot (20)

스프링 부트와 로깅
스프링 부트와 로깅스프링 부트와 로깅
스프링 부트와 로깅
 
How to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor NettyHow to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor Netty
 
Linux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old SecretsLinux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old Secrets
 
Filesystem Comparison: NFS vs GFS2 vs OCFS2
Filesystem Comparison: NFS vs GFS2 vs OCFS2Filesystem Comparison: NFS vs GFS2 vs OCFS2
Filesystem Comparison: NFS vs GFS2 vs OCFS2
 
Tools for Solving Performance Issues
Tools for Solving Performance IssuesTools for Solving Performance Issues
Tools for Solving Performance Issues
 
Prometheus – a next-gen Monitoring System
Prometheus – a next-gen Monitoring SystemPrometheus – a next-gen Monitoring System
Prometheus – a next-gen Monitoring System
 
Linux Locking Mechanisms
Linux Locking MechanismsLinux Locking Mechanisms
Linux Locking Mechanisms
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript Engine
 
Postgresql database administration volume 1
Postgresql database administration volume 1Postgresql database administration volume 1
Postgresql database administration volume 1
 
How We Reduced Performance Tuning Time by Orders of Magnitude with Database O...
How We Reduced Performance Tuning Time by Orders of Magnitude with Database O...How We Reduced Performance Tuning Time by Orders of Magnitude with Database O...
How We Reduced Performance Tuning Time by Orders of Magnitude with Database O...
 
Profiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf ToolsProfiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf Tools
 
Vagrant
Vagrant Vagrant
Vagrant
 
High Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando PatroniHigh Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando Patroni
 
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to Celery
 
Fluentd Overview, Now and Then
Fluentd Overview, Now and ThenFluentd Overview, Now and Then
Fluentd Overview, Now and Then
 
[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅
 
ClickHouse Keeper
ClickHouse KeeperClickHouse Keeper
ClickHouse Keeper
 
Better than you think: Handling JSON data in ClickHouse
Better than you think: Handling JSON data in ClickHouseBetter than you think: Handling JSON data in ClickHouse
Better than you think: Handling JSON data in ClickHouse
 
Altinity Cluster Manager: ClickHouse Management for Kubernetes and Cloud
Altinity Cluster Manager: ClickHouse Management for Kubernetes and CloudAltinity Cluster Manager: ClickHouse Management for Kubernetes and Cloud
Altinity Cluster Manager: ClickHouse Management for Kubernetes and Cloud
 

Viewers also liked

Logging in Python for large applications
Logging in Python for large applicationsLogging in Python for large applications
Logging in Python for large applicationsFayaz Yusuf Khan
 
A Curious Course on Coroutines and Concurrency
A Curious Course on Coroutines and ConcurrencyA Curious Course on Coroutines and Concurrency
A Curious Course on Coroutines and ConcurrencyDavid Beazley (Dabeaz LLC)
 
Il lavoro delle donne nel settore turismo
Il lavoro delle donne nel settore turismoIl lavoro delle donne nel settore turismo
Il lavoro delle donne nel settore turismoFormazioneTurismo
 
Bai tap cnc_0516
Bai tap cnc_0516Bai tap cnc_0516
Bai tap cnc_0516dung nong
 
Evaluation question 2
Evaluation question 2Evaluation question 2
Evaluation question 2beerogers
 
WiscNet 2016 Strategic Plan
WiscNet 2016 Strategic PlanWiscNet 2016 Strategic Plan
WiscNet 2016 Strategic PlanMaddy Covelli
 
Start Your Website for Free!
Start Your Website for Free!Start Your Website for Free!
Start Your Website for Free!Mario Peshev
 
Welcome to central web power point oct 2014
Welcome to central web power point oct 2014Welcome to central web power point oct 2014
Welcome to central web power point oct 2014Central Elementary
 
AppZero & GoGrid: Moving Windows Server Apps to Cloud in 3 Easy Steps
AppZero & GoGrid: Moving Windows Server Apps to Cloud in 3 Easy StepsAppZero & GoGrid: Moving Windows Server Apps to Cloud in 3 Easy Steps
AppZero & GoGrid: Moving Windows Server Apps to Cloud in 3 Easy StepsAppZero
 
Certificación Red Hat
Certificación Red HatCertificación Red Hat
Certificación Red HatRed Hat
 
Fraud-on-the-Market Theory: Significant Issues and Updates for 2014 and Beyon...
Fraud-on-the-Market Theory: Significant Issues and Updates for 2014 and Beyon...Fraud-on-the-Market Theory: Significant Issues and Updates for 2014 and Beyon...
Fraud-on-the-Market Theory: Significant Issues and Updates for 2014 and Beyon...Thomas LaPointe
 
2014 Anti-Corruption Public Procurement guide
2014 Anti-Corruption Public Procurement guide2014 Anti-Corruption Public Procurement guide
2014 Anti-Corruption Public Procurement guideDr Lendy Spires
 
Garcinia cambogia: nuovo estratto miracolose per perdere peso velocemente. Tu...
Garcinia cambogia: nuovo estratto miracolose per perdere peso velocemente. Tu...Garcinia cambogia: nuovo estratto miracolose per perdere peso velocemente. Tu...
Garcinia cambogia: nuovo estratto miracolose per perdere peso velocemente. Tu...picayunenationa85
 

Viewers also liked (20)

Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio
 
Logging in Python for large applications
Logging in Python for large applicationsLogging in Python for large applications
Logging in Python for large applications
 
A Curious Course on Coroutines and Concurrency
A Curious Course on Coroutines and ConcurrencyA Curious Course on Coroutines and Concurrency
A Curious Course on Coroutines and Concurrency
 
HSGR
HSGRHSGR
HSGR
 
Il lavoro delle donne nel settore turismo
Il lavoro delle donne nel settore turismoIl lavoro delle donne nel settore turismo
Il lavoro delle donne nel settore turismo
 
Bai tap cnc_0516
Bai tap cnc_0516Bai tap cnc_0516
Bai tap cnc_0516
 
Playrlic
PlayrlicPlayrlic
Playrlic
 
Evaluation question 2
Evaluation question 2Evaluation question 2
Evaluation question 2
 
WiscNet 2016 Strategic Plan
WiscNet 2016 Strategic PlanWiscNet 2016 Strategic Plan
WiscNet 2016 Strategic Plan
 
Start Your Website for Free!
Start Your Website for Free!Start Your Website for Free!
Start Your Website for Free!
 
Nbhtc pure
Nbhtc pureNbhtc pure
Nbhtc pure
 
Welcome to central web power point oct 2014
Welcome to central web power point oct 2014Welcome to central web power point oct 2014
Welcome to central web power point oct 2014
 
AppZero & GoGrid: Moving Windows Server Apps to Cloud in 3 Easy Steps
AppZero & GoGrid: Moving Windows Server Apps to Cloud in 3 Easy StepsAppZero & GoGrid: Moving Windows Server Apps to Cloud in 3 Easy Steps
AppZero & GoGrid: Moving Windows Server Apps to Cloud in 3 Easy Steps
 
Certificación Red Hat
Certificación Red HatCertificación Red Hat
Certificación Red Hat
 
Culturetoute N1
Culturetoute N1Culturetoute N1
Culturetoute N1
 
Fraud-on-the-Market Theory: Significant Issues and Updates for 2014 and Beyon...
Fraud-on-the-Market Theory: Significant Issues and Updates for 2014 and Beyon...Fraud-on-the-Market Theory: Significant Issues and Updates for 2014 and Beyon...
Fraud-on-the-Market Theory: Significant Issues and Updates for 2014 and Beyon...
 
Supranational Collaboration in Agricultural Research in Sub-Saharan Africa
Supranational Collaboration in Agricultural Research in Sub-Saharan AfricaSupranational Collaboration in Agricultural Research in Sub-Saharan Africa
Supranational Collaboration in Agricultural Research in Sub-Saharan Africa
 
Plan de trabajo
Plan de trabajoPlan de trabajo
Plan de trabajo
 
2014 Anti-Corruption Public Procurement guide
2014 Anti-Corruption Public Procurement guide2014 Anti-Corruption Public Procurement guide
2014 Anti-Corruption Public Procurement guide
 
Garcinia cambogia: nuovo estratto miracolose per perdere peso velocemente. Tu...
Garcinia cambogia: nuovo estratto miracolose per perdere peso velocemente. Tu...Garcinia cambogia: nuovo estratto miracolose per perdere peso velocemente. Tu...
Garcinia cambogia: nuovo estratto miracolose per perdere peso velocemente. Tu...
 

Similar to asyncio internals

Asynchronous Python at Kumparan
Asynchronous Python at KumparanAsynchronous Python at Kumparan
Asynchronous Python at KumparanBayu Aldi Yansyah
 
Seattle.rb 6.4
Seattle.rb 6.4Seattle.rb 6.4
Seattle.rb 6.4deanhudson
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Ansible for beginners ...?
Ansible for beginners ...?Ansible for beginners ...?
Ansible for beginners ...?shirou wakayama
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Samuel Lampa
 
Put on Your Asynchronous Hat and Node
Put on Your Asynchronous Hat and NodePut on Your Asynchronous Hat and Node
Put on Your Asynchronous Hat and NodeMarc Fasel
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingHoàng Lâm Huỳnh
 
Elixir/OTP for PHP developers
Elixir/OTP for PHP developersElixir/OTP for PHP developers
Elixir/OTP for PHP developersIgnacio Martín
 
OkAPI meet symfony, symfony meet OkAPI
OkAPI meet symfony, symfony meet OkAPIOkAPI meet symfony, symfony meet OkAPI
OkAPI meet symfony, symfony meet OkAPILukas Smith
 
Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Eugene Lazutkin
 
BUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOBUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOMykola Novik
 
Node.js basics
Node.js basicsNode.js basics
Node.js basicsBen Lin
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Allan Marques Baptista
 

Similar to asyncio internals (20)

Asynchronous Python at Kumparan
Asynchronous Python at KumparanAsynchronous Python at Kumparan
Asynchronous Python at Kumparan
 
ZF3 introduction
ZF3 introductionZF3 introduction
ZF3 introduction
 
Seattle.rb 6.4
Seattle.rb 6.4Seattle.rb 6.4
Seattle.rb 6.4
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Ansible for beginners ...?
Ansible for beginners ...?Ansible for beginners ...?
Ansible for beginners ...?
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Put on Your Asynchronous Hat and Node
Put on Your Asynchronous Hat and NodePut on Your Asynchronous Hat and Node
Put on Your Asynchronous Hat and Node
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Elixir/OTP for PHP developers
Elixir/OTP for PHP developersElixir/OTP for PHP developers
Elixir/OTP for PHP developers
 
Operating System Assignment Help
Operating System Assignment HelpOperating System Assignment Help
Operating System Assignment Help
 
OkAPI meet symfony, symfony meet OkAPI
OkAPI meet symfony, symfony meet OkAPIOkAPI meet symfony, symfony meet OkAPI
OkAPI meet symfony, symfony meet OkAPI
 
Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
What`s new in Java 7
What`s new in Java 7What`s new in Java 7
What`s new in Java 7
 
Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.
 
Lsn07_Conditionals.ppt
Lsn07_Conditionals.pptLsn07_Conditionals.ppt
Lsn07_Conditionals.ppt
 
BUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOBUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIO
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
 

More from Saúl Ibarra Corretgé

JanusCon 2024: Mom there are robots in my meeting
JanusCon 2024: Mom there are robots in my meetingJanusCon 2024: Mom there are robots in my meeting
JanusCon 2024: Mom there are robots in my meetingSaúl Ibarra Corretgé
 
Challenges running Jitsi Meet at scale during the pandemic
Challenges running Jitsi Meet at scale during the pandemicChallenges running Jitsi Meet at scale during the pandemic
Challenges running Jitsi Meet at scale during the pandemicSaúl Ibarra Corretgé
 
The Road to End-to-End Encryption in Jitsi Meet
The Road to End-to-End Encryption in Jitsi MeetThe Road to End-to-End Encryption in Jitsi Meet
The Road to End-to-End Encryption in Jitsi MeetSaúl Ibarra Corretgé
 
Jitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: our tale of blood, sweat, tears and loveJitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: our tale of blood, sweat, tears and loveSaúl Ibarra Corretgé
 
Jitsi Meet: Video conferencing for the privacy minded
Jitsi Meet: Video conferencing for the privacy mindedJitsi Meet: Video conferencing for the privacy minded
Jitsi Meet: Video conferencing for the privacy mindedSaúl Ibarra Corretgé
 
Get a room! Spot: the ultimate physical meeting room experience
Get a room! Spot: the ultimate physical meeting room experienceGet a room! Spot: the ultimate physical meeting room experience
Get a room! Spot: the ultimate physical meeting room experienceSaúl Ibarra Corretgé
 
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCGoing Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCSaúl Ibarra Corretgé
 
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCGoing Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCSaúl Ibarra Corretgé
 
Jitsi: state-of-the-art video conferencing you can self-host
Jitsi: state-of-the-art video conferencing you can self-hostJitsi: state-of-the-art video conferencing you can self-host
Jitsi: state-of-the-art video conferencing you can self-hostSaúl Ibarra Corretgé
 
WebRTC: El epicentro de la videoconferencia y IoT
WebRTC: El epicentro de la videoconferencia y IoTWebRTC: El epicentro de la videoconferencia y IoT
WebRTC: El epicentro de la videoconferencia y IoTSaúl Ibarra Corretgé
 
libuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/olibuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/oSaúl Ibarra Corretgé
 
Videoconferencias: el santo grial de WebRTC
Videoconferencias: el santo grial de WebRTCVideoconferencias: el santo grial de WebRTC
Videoconferencias: el santo grial de WebRTCSaúl Ibarra Corretgé
 
SylkServer: State of the art RTC application server
SylkServer: State of the art RTC application serverSylkServer: State of the art RTC application server
SylkServer: State of the art RTC application serverSaúl Ibarra Corretgé
 
Escalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincherasEscalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincherasSaúl Ibarra Corretgé
 

More from Saúl Ibarra Corretgé (20)

JanusCon 2024: Mom there are robots in my meeting
JanusCon 2024: Mom there are robots in my meetingJanusCon 2024: Mom there are robots in my meeting
JanusCon 2024: Mom there are robots in my meeting
 
Challenges running Jitsi Meet at scale during the pandemic
Challenges running Jitsi Meet at scale during the pandemicChallenges running Jitsi Meet at scale during the pandemic
Challenges running Jitsi Meet at scale during the pandemic
 
The Road to End-to-End Encryption in Jitsi Meet
The Road to End-to-End Encryption in Jitsi MeetThe Road to End-to-End Encryption in Jitsi Meet
The Road to End-to-End Encryption in Jitsi Meet
 
Jitsi: State of the Union 2020
Jitsi: State of the Union 2020Jitsi: State of the Union 2020
Jitsi: State of the Union 2020
 
Jitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: our tale of blood, sweat, tears and loveJitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: our tale of blood, sweat, tears and love
 
Jitsi Meet: Video conferencing for the privacy minded
Jitsi Meet: Video conferencing for the privacy mindedJitsi Meet: Video conferencing for the privacy minded
Jitsi Meet: Video conferencing for the privacy minded
 
Jitsi - Estado de la unión 2019
Jitsi - Estado de la unión 2019Jitsi - Estado de la unión 2019
Jitsi - Estado de la unión 2019
 
Get a room! Spot: the ultimate physical meeting room experience
Get a room! Spot: the ultimate physical meeting room experienceGet a room! Spot: the ultimate physical meeting room experience
Get a room! Spot: the ultimate physical meeting room experience
 
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCGoing Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTC
 
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCGoing Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTC
 
Jitsi: Estado de la Unión (2018)
Jitsi: Estado de la Unión (2018)Jitsi: Estado de la Unión (2018)
Jitsi: Estado de la Unión (2018)
 
Jitsi: state-of-the-art video conferencing you can self-host
Jitsi: state-of-the-art video conferencing you can self-hostJitsi: state-of-the-art video conferencing you can self-host
Jitsi: state-of-the-art video conferencing you can self-host
 
WebRTC: El epicentro de la videoconferencia y IoT
WebRTC: El epicentro de la videoconferencia y IoTWebRTC: El epicentro de la videoconferencia y IoT
WebRTC: El epicentro de la videoconferencia y IoT
 
Jitsi: Open Source Video Conferencing
Jitsi: Open Source Video ConferencingJitsi: Open Source Video Conferencing
Jitsi: Open Source Video Conferencing
 
Jitsi: State of the Union
Jitsi: State of the UnionJitsi: State of the Union
Jitsi: State of the Union
 
libuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/olibuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/o
 
Videoconferencias: el santo grial de WebRTC
Videoconferencias: el santo grial de WebRTCVideoconferencias: el santo grial de WebRTC
Videoconferencias: el santo grial de WebRTC
 
SylkServer: State of the art RTC application server
SylkServer: State of the art RTC application serverSylkServer: State of the art RTC application server
SylkServer: State of the art RTC application server
 
Escalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincherasEscalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincheras
 
A deep dive into libuv
A deep dive into libuvA deep dive into libuv
A deep dive into libuv
 

Recently uploaded

JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaRTTS
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka DoktorováCzechDreamin
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...CzechDreamin
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesThousandEyes
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Thierry Lestable
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...Sri Ambati
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...Product School
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 

Recently uploaded (20)

JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 

asyncio internals

  • 1. asyncio internals Saúl Ibarra Corretgé @saghul PyGrunn 2014 Friday, May 9, 14
  • 2. Intro New asynchronous I/O framework for Python PEP-3156 Python >= 3.3 (backport available: Trollius) Uses new language features: yield from Designed to interoperate with other frameworks You went to Rodrigo’s talk earlier today, right? Friday, May 9, 14
  • 4. Architecture Event loop Coroutines, Futures and Tasks Transports, Protocols and Streams I’ll cover these Homework! Friday, May 9, 14
  • 7. There is no abstraction for an “event” It runs callbacks which are put in a queue Callbacks can be scheduled due to i/o, time or user desire The event loop acts as an implicit scheduler Friday, May 9, 14
  • 8. Sim plified def call_soon(self, callback, *args): handle = events.Handle(callback, args, self) self._ready.append(handle) return handle Friday, May 9, 14
  • 9. events.Handle is like a “callbak wrapper” The ready queue is a deque Once per loop iteration al handles in the ready queue are executed Friday, May 9, 14
  • 10. def call_later(self, delay, callback, *args): return self.call_at(self.time() + delay, callback, *args) def call_at(self, when, callback, *args): timer = events.TimerHandle(when, callback, args, self) heapq.heappush(self._scheduled, timer) return timer Sim plified Friday, May 9, 14
  • 11. Timers are stored in a heap (loop._scheduled) TimerHandle subclasses Handle, but stores the time when it’s due and has comparison methods for keeping the heap sorted by due time Friday, May 9, 14
  • 12. ntodo = len(self._ready) for i in range(ntodo): handle = self._ready.popleft() if not handle._cancelled: handle._run() handle = None # break cycles Friday, May 9, 14
  • 13. This is the single place where the ready queue is iterated over A thread-safe iteration method is used, since other threads could modify the ready queue (see call_soon_threadsafe) If any handles are scheduled while the ready queue is being processed, they will be run on the next loop iteration Friday, May 9, 14
  • 14. Different polling mechanisms on Unix: select, poll, epoll, kqueue, devpoll Windows is a completely different beast Different paradigms: readyness vs completion APIs are provided for both I/O handling Friday, May 9, 14
  • 15. I/O handling APIs Readyness style add_reader/add_writer remove_reader/remove_writer Completion style sock_recv/sock_sendall sock_connect/sock_accept Friday, May 9, 14
  • 16. import selectors New module in Python 3.4 Consistent interface to Unix polling mechanisms On Windows it uses select() 64 file descriptors default* limit - WEBSCALE! IOCP is the way to go, but has a different API Caveat emptor: doesn’t work for file i/o Friday, May 9, 14
  • 17. Sim plified def add_reader(self, fd, callback, *args): handle = events.Handle(callback, args, self) try: key = self._selector.get_key(fd) except KeyError: self._selector.register(fd, selectors.EVENT_READ, (handle, None)) else: mask, (reader, writer) = key.events, key.data self._selector.modify(fd, mask | selectors.EVENT_READ, (handle, writer)) if reader is not None: reader.cancel() Friday, May 9, 14
  • 18. The selector key stores the fd, events and user provided arbitrary data In this case the arbitrary data is the reader, writer handle tuple Only one reader and writer per fd are allowed Friday, May 9, 14
  • 19. 1.Calculate timeout 2.Block for I/O 3.Process I/O events: schedule callbacks 4.Process timers: schedule callbacks 5.Run pending callbacks Polling for I/O Friday, May 9, 14
  • 20. timeout = None if self._ready: timeout = 0 elif self._scheduled: # Compute the desired timeout. when = self._scheduled[0]._when deadline = max(0, when - self.time()) if timeout is None: timeout = deadline else: timeout = min(timeout, deadline) event_list = self._selector.select(timeout) self._process_events(event_list) end_time = self.time() while self._scheduled: handle = self._scheduled[0] if handle._when >= end_time: break handle = heapq.heappop(self._scheduled) self._ready.append(handle) # run all handles in the ready queue... Sim plified Friday, May 9, 14
  • 21. If timeout is None an infinite poll is performed _process_events puts the read / write handles in the ready queue, if applicable Friday, May 9, 14
  • 22. def call_soon_threadsafe(self, callback, *args): handle = self._call_soon(callback, args) self._write_to_self() return handle Sim plified Friday, May 9, 14
  • 23. The event loop has the read end of a socketpair added to the selector When _write_to_self is called the loop will be “waken up” from the select/poll/epoll_wait/kevent syscall Friday, May 9, 14
  • 24. Coroutines, Futures & Tasks Friday, May 9, 14
  • 25. Generator functions, can also receive values Use the @asyncio.coroutine decorator Does extra checks in debug mode Serves as documentation Chain them with yield from Coroutines Friday, May 9, 14
  • 26. Not actually PEP-3148 (concurrent.futures) API almost identical Represent a value which is not there yet yield from can be used to wait for it! asyncio.wrap_future can be used to wrap a PEP-3148 Future into one of these Futures Friday, May 9, 14
  • 27. f = Future() Usually a future will be the result of a function f.set_result / f.set_exception Someone will set the result eventually yield from f Wait until the result arrives add_done_callback / remove_done_callback Callback based interface Friday, May 9, 14
  • 28. def set_result(self, result): if self._state != _PENDING: raise InvalidStateError('{}: {!r}'.format(self._state, self)) self._result = result self._state = _FINISHED self._schedule_callbacks() def _schedule_callbacks(self): callbacks = self._callbacks[:] if not callbacks: return self._callbacks[:] = [] for callback in callbacks: self._loop.call_soon(callback, self) Friday, May 9, 14
  • 29. After the result or exception is set all callbacks added with Future.add_done_callback are called Note how callbacks are scheduled in the event loop using call_soon Friday, May 9, 14
  • 30. Sim plified def sock_connect(self, sock, address): fut = futures.Future(loop=self) self._sock_connect(fut, False, sock, address) return fut def _sock_connect(self, fut, registered, sock, address): fd = sock.fileno() if registered: self.remove_writer(fd) if fut.cancelled(): return try: if not registered: sock.connect(address) else: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: raise OSError(err, 'Connect call failed %s' % (address,)) except (BlockingIOError, InterruptedError): self.add_writer(fd, self._sock_connect, fut, True, sock, address) except Exception as exc: fut.set_exception(exc) else: fut.set_result(None) Friday, May 9, 14
  • 31. Not a coroutine, but we can wait on it using yield from because it returns a Future The Uncallback Pattern (TM) Hey, look at those nice exceptions: BlockingIOError, InterruptedError Much nicer than checking if errno is EWOULDBLOCK or EINTR Friday, May 9, 14
  • 32. def run_until_complete(self, future): future = tasks.async(future, loop=self) future.add_done_callback(_raise_stop_error) self.run_forever() future.remove_done_callback(_raise_stop_error) if not future.done(): raise RuntimeError('Event loop stopped before Future completed.') return future.result() Friday, May 9, 14
  • 33. Loop.run_forever will run the loop until Loop.stop is called _raise_stop_error is an implementation detail, it causes an exception to bubble up and makes run_forever return Friday, May 9, 14
  • 34. def __iter__(self): if not self.done(): self._blocking = True yield self # This tells Task to wait for completion. assert self.done(), "yield from wasn't used with future" return self.result() # May raise too. Friday, May 9, 14
  • 35. Returning a value from __iter__ is the same as raising StopIteration(value) The _blocking flag is used to check if yield future was used intead of yield from future Task has a way to wait on a Future if yielded to it, also checks that yield from was used (_blocking flag) Friday, May 9, 14
  • 37. Unit of concurrent asynchronous work It’s actually a coroutine wrapped in a Future Magic! Schedules callbacks using loop.call_soon Use asyncio.async to run a coroutine in a Task Tasks Friday, May 9, 14
  • 38. import asyncio @asyncio.coroutine def f(n, x): while True: print(n) yield from asyncio.sleep(x) loop = asyncio.get_event_loop() asyncio.async(f('f1', 0.5)) asyncio.async(f('f2', 1.5)) loop.run_forever() Friday, May 9, 14
  • 39. Both coroutines will run concurrently asyncio.async returns a Task if a coroutine was passed, or the unchanged value if a Future was passed Go and check how asyncio.sleep is implemented, it’s really simple! Friday, May 9, 14
  • 40. def __init__(self, coro, *, loop=None): assert iscoroutine(coro), repr(coro) # Not a coroutine function! super().__init__(loop=loop) self._coro = iter(coro) # Use the iterator just in case. self._fut_waiter = None self._loop.call_soon(self._step) Sim plified Friday, May 9, 14
  • 41. Tasks are not run immediately, the actual work is done by Task._step, which is scheduled with loop.call_soon _fut_waiter is used to store a Future which this Task is waiting for Friday, May 9, 14
  • 42. Sim plified def _step(self, value=None, exc=None): assert not self.done(), '_step(): already done' coro = self._coro self._fut_waiter = None try: if exc is not None: result = coro.throw(exc) elif value is not None: result = coro.send(value) else: result = next(coro) except StopIteration as exc: self.set_result(exc.value) except Exception as exc: self.set_exception(exc) except BaseException as exc: self.set_exception(exc) raise else: if isinstance(result, futures.Future): # Yielded Future must come from Future.__iter__(). if result._blocking: result._blocking = False result.add_done_callback(self._wakeup) self._fut_waiter = result else: # error... elif result is None: # Bare yield relinquishes control for one event loop iteration. self._loop.call_soon(self._step) else: # error... Friday, May 9, 14
  • 43. The Magic (TM) The coroutine is stepped over until it finishes Note the check of _blocking to verify yield vs yield from usage The _wakeup function will schedule _step with either a result or an exception At any point in time, either _step is scheduled or _fut_waiter is not None Friday, May 9, 14
  • 44. There is a lot more in asyncio Go read PEP-3156 Don’t be afraid of looking under the hood Don’t rely on internals, they are implementation details Join the mailing list, check the third party libraries! raise SystemExit “I hear and I forget. I see and I remember. I do and I understand.” - Confucius Friday, May 9, 14