SlideShare a Scribd company logo
1 of 31
Download to read offline
How do event loops
 work in Python?
    Saúl Ibarra Corretgé




      FOSDEM 2013
print(self)

• Hi there!

• @saghul

• I work on VoIP and Real Time Communications

• Python and C are my tools
try: sockets
from __future__ import print_function

import socket

server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
server.bind(('127.0.0.1', 1234))
server.listen(10)
print("Server listening on: {}".format(server.getsockname()))

client, addr = server.accept()
print("Client connected: {}".format(addr))

while True:
    data = client.recv(4096)
    if not data:
        print("Client has disconnected")
        break
    client.send(data.upper())

server.close()
except Exception:
• We can only handle one client at a time!

• Solutions for handling multiple clients

   • Threads

   • I/O multiplexing

• Check the C10K problem if you haven’t already!

   • http://www.kegel.com/c10k.html
try: sockets + threads
from __future__ import print_function

import socket
import thread

def handle_client(client, addr):
    print("Client connected: {}".format(addr))
    while True:
        data = client.recv(4096)
        if not data:
            print("Client has disconnected")
            break
        client.send(data.upper())

server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
server.bind(('127.0.0.1', 1234))
server.listen(10)
print("Server listening on: {}".format(server.getsockname()))

while True:
    client, addr = server.accept()
    thread.start_new_thread(handle_client, (client, addr))
except Exception:
• Threads have overhead

  • Stack size

  • Context switching

• Synchronization

• GIL?

  • Not for I/O!
I/O multiplexing
• Examine and block for I/O in multiple file
  descriptors at the same time

   • Single thread

• A file descriptor is ready if the corresponding I/O
  operation can be performed without blocking

• File descriptor has to be set to be non-blocking
I/O multiplexing (II)

1. Put file descriptors in non-blocking mode

2. Add file descriptors to a I/O multiplexor

3. Block for some time

4. Perform blocking operations on file descriptors
   which are ready
def set_nonblocking
def set_nonblocking(fdobj):
    try:
         setblocking = fdobj.setblocking
    except AttributeError:
         try:
              import fcntl
         except ImportError:
              raise NotImplementedError
         try:
              fd = fdobj.fileno()
         except AttributeError:
              fd = fdobj
         flags = fcntl.fcntl(fd, fcntl.F_GETFL)
         fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
    else:
         setblocking(False)
select

• Lowest common denominator I/O multiplexor

• Takes a list of “readers”, “writers”, “exceptional
  conditions” and a timeout

• Limit of FD_SETSIZE file descriptors, usually 1024

• Processing takes O(number of fds)
epoll

• “A better select”

• No FD_SETSIZE limit!

• Processing takes O(1) time!

• Linux only
Other I/O
         multiplexors
• kqueue

  • Like epoll but for Max OSX and BSD

• poll

  • Like select but without a limit of file descriptors

  • O(number of file descriptors) processing time

  • Very broken on some systems (OSX 10.3-5)
sys.platform == “win32”
  • Windows supports select

     • 64 file descriptors per thread - WAT

  • Starting with Vista WSAPoll (poll) is supported

     • It’s broken - http://daniel.haxx.se/blog/
       2012/10/10/wsapoll-is-broken/

  • IOCP is the good stuff

     • Based on completion, not readiness
edge/level triggering
• Level triggering (the most common)

   • You get notified when the condition is present

• Edge triggering

   • You get notified when the condition happens

• epoll and kqueue support both mechanisms

• IOCP is kind-of edge-triggered epoll
Event loop libraries
            epoll, IOCP on
                           File I/O
           kqueue windows

 libev      YES      NO      libeio

libevent    YES      YES      NO

 libuv      YES      YES      YES
Event loop libraries
        (II)
        1. Update loop time

         2. Process timers

      3. Process idle handles

     4. Process prepare handles

          5. Block for I/O

     6. Process check handles
libuv: the power
underneath nodeJS
nodeJS <= 0.4.x

                   node standard library
JavaScript

  C / C++
                      node bindings


              V8           libev       libeio
nodeJS >= 0.6.x

                   node standard library
JavaScript

  C / C++
                      node bindings


              V8                 libuv
libuv
• Originally based on libev + libeio + IOCP

• Now: epoll + kqueue + event ports + IOCP + file I/O

• TCP, UDP, named pipes, TTY

• Nice additions: interface addresses, process title, ...

• Most complete cross platform networking library

• Python bindings - pyuv
import pyuv

• Written in C, wraps everything libuv has to offer

• Python >= 2.6, supports Python 3!

• Works on Windows

• https://github.com/saghul/pyuv
from __future__ import print_function

import signal
import pyuv

def on_read(client, data, error):
    if data is None:
        print("Client read error: {}".format(pyuv.errno.strerror(error)))
        client.close()
        clients.remove(client)
        return
    client.write(data.upper())

def on_connection(server, error):
    client = pyuv.TCP(server.loop)
    server.accept(client)
    clients.append(client)
    client.start_read(on_read)
    print("Client connected: {}".format(client.getpeername()))

def signal_cb(handle, signum):
    [c.close() for c in clients]
    signal_h.close()
    server.close()

clients = []
loop = pyuv.Loop.default_loop()
server = pyuv.TCP(loop)
server.bind(("127.0.0.1", 1234))
server.listen(on_connection)
signal_h = pyuv.Signal(loop)
signal_h.start(signal_cb, signal.SIGINT)
loop.run()
import pyuv

• Experiments in replacing event loops of common
  Python networking frameworks

  • Twisted - https://github.com/saghul/twisted-pyuv

  • Tornado - https://github.com/saghul/tornado-pyuv

  • Gevent - https://github.com/saghul/uvent
import pyuv

• gaffer: application deployment and supervisor

   • https://github.com/benoitc/gaffer

• ts_analyzer: realtime analysis of multicast video
  streams

   • https://github.com/tijmenNL/ts_analyzer
The Python
 async I/O problem
• Each framework uses it’s own event loop
  implementation

• Protocols aren’t reusable

• PEP-3156 to the rescue!

   • For Python >= 3.3

• Reference implementation (Tulip)
  https://code.google.com/p/tulip/
import rose

• PEP-3156 EventLoop implementation using pyuv

• pyuv.Poll: high performance level triggered I/O
  (works on Windows as well!)

   • Uses fairy dust covered unicorns

• https://github.com/saghul/rose
import rose
import signal
from rose import events, protocols

class EchoProtocol(protocols.Protocol):
    def connection_made(self, transport):
        # TODO: Transport should probably expose getsockname/getpeername
        print("Client connected: {}".format(transport._sock.getpeername()))
        self.transport = transport
    def data_received(self, data):
        self.transport.write(data.upper())
    def eof_received(self):
        self.transport.close()
    def connection_lost(self, exc):
        print("Client closed connection")

reactor = events.new_event_loop()
events.set_event_loop(reactor)

reactor.start_serving(EchoProtocol, '127.0.0.1', 1234)
reactor.add_signal_handler(signal.SIGINT, reactor.stop)

reactor.run()
saghul

More Related Content

What's hot

Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 
Top 1000 Java Interview Questions Includes Spring, Hibernate, Microservices, ...
Top 1000 Java Interview Questions Includes Spring, Hibernate, Microservices, ...Top 1000 Java Interview Questions Includes Spring, Hibernate, Microservices, ...
Top 1000 Java Interview Questions Includes Spring, Hibernate, Microservices, ...Ankit Kumar
 
トピックブランチとは
トピックブランチとはトピックブランチとは
トピックブランチとはnakajima_yuji
 
Javaバイトコード入門
Javaバイトコード入門Javaバイトコード入門
Javaバイトコード入門Kota Mizushima
 
名は体を表していますか
名は体を表していますか名は体を表していますか
名は体を表していますかinfinite_loop
 
Estrutura de Dados - Aula de revisão de c na prática
Estrutura de Dados - Aula de revisão de c na práticaEstrutura de Dados - Aula de revisão de c na prática
Estrutura de Dados - Aula de revisão de c na práticaLeinylson Fontinele
 
Java Just-In-Timeコンパイラ
Java Just-In-TimeコンパイラJava Just-In-Timeコンパイラ
Java Just-In-TimeコンパイラKazuaki Ishizaki
 
Dotnet Basics Presentation
Dotnet Basics PresentationDotnet Basics Presentation
Dotnet Basics PresentationSudhakar Sharma
 
Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2YEONG-CHEON YOU
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructorHaresh Jaiswal
 
Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentationAhasanul Kalam Akib
 
Rustで DDD を実践しながら API サーバーを実装・構築した(つもり)
Rustで DDD を実践しながら API サーバーを実装・構築した(つもり)Rustで DDD を実践しながら API サーバーを実装・構築した(つもり)
Rustで DDD を実践しながら API サーバーを実装・構築した(つもり)ShogoOkazaki
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++Learn By Watch
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
ドメインロジックの実装方法とドメイン駆動設計
ドメインロジックの実装方法とドメイン駆動設計ドメインロジックの実装方法とドメイン駆動設計
ドメインロジックの実装方法とドメイン駆動設計Tadayoshi Sato
 
Orientação a Objetos em Python
Orientação a Objetos em PythonOrientação a Objetos em Python
Orientação a Objetos em PythonLuciano Ramalho
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 

What's hot (20)

Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Top 1000 Java Interview Questions Includes Spring, Hibernate, Microservices, ...
Top 1000 Java Interview Questions Includes Spring, Hibernate, Microservices, ...Top 1000 Java Interview Questions Includes Spring, Hibernate, Microservices, ...
Top 1000 Java Interview Questions Includes Spring, Hibernate, Microservices, ...
 
トピックブランチとは
トピックブランチとはトピックブランチとは
トピックブランチとは
 
Javaバイトコード入門
Javaバイトコード入門Javaバイトコード入門
Javaバイトコード入門
 
名は体を表していますか
名は体を表していますか名は体を表していますか
名は体を表していますか
 
Estrutura de Dados - Aula de revisão de c na prática
Estrutura de Dados - Aula de revisão de c na práticaEstrutura de Dados - Aula de revisão de c na prática
Estrutura de Dados - Aula de revisão de c na prática
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Java Just-In-Timeコンパイラ
Java Just-In-TimeコンパイラJava Just-In-Timeコンパイラ
Java Just-In-Timeコンパイラ
 
Dotnet Basics Presentation
Dotnet Basics PresentationDotnet Basics Presentation
Dotnet Basics Presentation
 
Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentation
 
Rustで DDD を実践しながら API サーバーを実装・構築した(つもり)
Rustで DDD を実践しながら API サーバーを実装・構築した(つもり)Rustで DDD を実践しながら API サーバーを実装・構築した(つもり)
Rustで DDD を実践しながら API サーバーを実装・構築した(つもり)
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
ドメインロジックの実装方法とドメイン駆動設計
ドメインロジックの実装方法とドメイン駆動設計ドメインロジックの実装方法とドメイン駆動設計
ドメインロジックの実装方法とドメイン駆動設計
 
Orientação a Objetos em Python
Orientação a Objetos em PythonOrientação a Objetos em Python
Orientação a Objetos em Python
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 

Viewers also liked

A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleSaúl Ibarra Corretgé
 
Vert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingVert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingAlex Derkach
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Building microservices with vert.x 3.0
Building microservices with vert.x 3.0Building microservices with vert.x 3.0
Building microservices with vert.x 3.0Agraj Mangal
 
Pythonによる非同期プログラミング入門
Pythonによる非同期プログラミング入門Pythonによる非同期プログラミング入門
Pythonによる非同期プログラミング入門Hironori Sekine
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using PythonAyun Park
 
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over WebsocketIntroduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocketsametmax
 
Namespaces and cgroups - the basis of Linux containers
Namespaces and cgroups - the basis of Linux containersNamespaces and cgroups - the basis of Linux containers
Namespaces and cgroups - the basis of Linux containersKernel TLV
 

Viewers also liked (12)

A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
Vert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingVert.x – The problem of real-time data binding
Vert.x – The problem of real-time data binding
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Building microservices with vert.x 3.0
Building microservices with vert.x 3.0Building microservices with vert.x 3.0
Building microservices with vert.x 3.0
 
Pythonによる非同期プログラミング入門
Pythonによる非同期プログラミング入門Pythonによる非同期プログラミング入門
Pythonによる非同期プログラミング入門
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python
 
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over WebsocketIntroduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
 
Namespaces and cgroups - the basis of Linux containers
Namespaces and cgroups - the basis of Linux containersNamespaces and cgroups - the basis of Linux containers
Namespaces and cgroups - the basis of Linux containers
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
 

Similar to How do event loops work in Python?

Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilitiesVorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilitiesDefconRussia
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?hawkowl
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)Tech in Asia ID
 
Balázs Bucsay - XFLTReaT: Building a Tunnel
Balázs Bucsay - XFLTReaT: Building a TunnelBalázs Bucsay - XFLTReaT: Building a Tunnel
Balázs Bucsay - XFLTReaT: Building a Tunnelhacktivity
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.jsPiotr Pelczar
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
Utilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIUtilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIOliver Busse
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionPrasoon Kumar
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...Hackito Ergo Sum
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Felix Geisendörfer
 
DevopsItalia2015 - DHCP at Facebook - Evolution of an infrastructure
DevopsItalia2015 - DHCP at Facebook - Evolution of an infrastructureDevopsItalia2015 - DHCP at Facebook - Evolution of an infrastructure
DevopsItalia2015 - DHCP at Facebook - Evolution of an infrastructureAngelo Failla
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Christian Joudrey
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101Rami Sayar
 

Similar to How do event loops work in Python? (20)

Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilitiesVorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
 
Balázs Bucsay - XFLTReaT: Building a Tunnel
Balázs Bucsay - XFLTReaT: Building a TunnelBalázs Bucsay - XFLTReaT: Building a Tunnel
Balázs Bucsay - XFLTReaT: Building a Tunnel
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
 
Introdution to Node.js
Introdution to Node.jsIntrodution to Node.js
Introdution to Node.js
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Utilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIUtilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino API
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?
 
DevopsItalia2015 - DHCP at Facebook - Evolution of an infrastructure
DevopsItalia2015 - DHCP at Facebook - Evolution of an infrastructureDevopsItalia2015 - DHCP at Facebook - Evolution of an infrastructure
DevopsItalia2015 - DHCP at Facebook - Evolution of an infrastructure
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101
 

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

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 

Recently uploaded (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

How do event loops work in Python?

  • 1. How do event loops work in Python? Saúl Ibarra Corretgé FOSDEM 2013
  • 2. print(self) • Hi there! • @saghul • I work on VoIP and Real Time Communications • Python and C are my tools
  • 3. try: sockets from __future__ import print_function import socket server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) server.bind(('127.0.0.1', 1234)) server.listen(10) print("Server listening on: {}".format(server.getsockname())) client, addr = server.accept() print("Client connected: {}".format(addr)) while True: data = client.recv(4096) if not data: print("Client has disconnected") break client.send(data.upper()) server.close()
  • 4. except Exception: • We can only handle one client at a time! • Solutions for handling multiple clients • Threads • I/O multiplexing • Check the C10K problem if you haven’t already! • http://www.kegel.com/c10k.html
  • 5. try: sockets + threads from __future__ import print_function import socket import thread def handle_client(client, addr): print("Client connected: {}".format(addr)) while True: data = client.recv(4096) if not data: print("Client has disconnected") break client.send(data.upper()) server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) server.bind(('127.0.0.1', 1234)) server.listen(10) print("Server listening on: {}".format(server.getsockname())) while True: client, addr = server.accept() thread.start_new_thread(handle_client, (client, addr))
  • 6. except Exception: • Threads have overhead • Stack size • Context switching • Synchronization • GIL? • Not for I/O!
  • 7. I/O multiplexing • Examine and block for I/O in multiple file descriptors at the same time • Single thread • A file descriptor is ready if the corresponding I/O operation can be performed without blocking • File descriptor has to be set to be non-blocking
  • 8. I/O multiplexing (II) 1. Put file descriptors in non-blocking mode 2. Add file descriptors to a I/O multiplexor 3. Block for some time 4. Perform blocking operations on file descriptors which are ready
  • 9. def set_nonblocking def set_nonblocking(fdobj): try: setblocking = fdobj.setblocking except AttributeError: try: import fcntl except ImportError: raise NotImplementedError try: fd = fdobj.fileno() except AttributeError: fd = fdobj flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) else: setblocking(False)
  • 10. select • Lowest common denominator I/O multiplexor • Takes a list of “readers”, “writers”, “exceptional conditions” and a timeout • Limit of FD_SETSIZE file descriptors, usually 1024 • Processing takes O(number of fds)
  • 11.
  • 12. epoll • “A better select” • No FD_SETSIZE limit! • Processing takes O(1) time! • Linux only
  • 13. Other I/O multiplexors • kqueue • Like epoll but for Max OSX and BSD • poll • Like select but without a limit of file descriptors • O(number of file descriptors) processing time • Very broken on some systems (OSX 10.3-5)
  • 14. sys.platform == “win32” • Windows supports select • 64 file descriptors per thread - WAT • Starting with Vista WSAPoll (poll) is supported • It’s broken - http://daniel.haxx.se/blog/ 2012/10/10/wsapoll-is-broken/ • IOCP is the good stuff • Based on completion, not readiness
  • 15. edge/level triggering • Level triggering (the most common) • You get notified when the condition is present • Edge triggering • You get notified when the condition happens • epoll and kqueue support both mechanisms • IOCP is kind-of edge-triggered epoll
  • 16.
  • 17. Event loop libraries epoll, IOCP on File I/O kqueue windows libev YES NO libeio libevent YES YES NO libuv YES YES YES
  • 18. Event loop libraries (II) 1. Update loop time 2. Process timers 3. Process idle handles 4. Process prepare handles 5. Block for I/O 6. Process check handles
  • 20. nodeJS <= 0.4.x node standard library JavaScript C / C++ node bindings V8 libev libeio
  • 21. nodeJS >= 0.6.x node standard library JavaScript C / C++ node bindings V8 libuv
  • 22. libuv • Originally based on libev + libeio + IOCP • Now: epoll + kqueue + event ports + IOCP + file I/O • TCP, UDP, named pipes, TTY • Nice additions: interface addresses, process title, ... • Most complete cross platform networking library • Python bindings - pyuv
  • 23. import pyuv • Written in C, wraps everything libuv has to offer • Python >= 2.6, supports Python 3! • Works on Windows • https://github.com/saghul/pyuv
  • 24. from __future__ import print_function import signal import pyuv def on_read(client, data, error): if data is None: print("Client read error: {}".format(pyuv.errno.strerror(error))) client.close() clients.remove(client) return client.write(data.upper()) def on_connection(server, error): client = pyuv.TCP(server.loop) server.accept(client) clients.append(client) client.start_read(on_read) print("Client connected: {}".format(client.getpeername())) def signal_cb(handle, signum): [c.close() for c in clients] signal_h.close() server.close() clients = [] loop = pyuv.Loop.default_loop() server = pyuv.TCP(loop) server.bind(("127.0.0.1", 1234)) server.listen(on_connection) signal_h = pyuv.Signal(loop) signal_h.start(signal_cb, signal.SIGINT) loop.run()
  • 25. import pyuv • Experiments in replacing event loops of common Python networking frameworks • Twisted - https://github.com/saghul/twisted-pyuv • Tornado - https://github.com/saghul/tornado-pyuv • Gevent - https://github.com/saghul/uvent
  • 26. import pyuv • gaffer: application deployment and supervisor • https://github.com/benoitc/gaffer • ts_analyzer: realtime analysis of multicast video streams • https://github.com/tijmenNL/ts_analyzer
  • 27. The Python async I/O problem • Each framework uses it’s own event loop implementation • Protocols aren’t reusable • PEP-3156 to the rescue! • For Python >= 3.3 • Reference implementation (Tulip) https://code.google.com/p/tulip/
  • 28. import rose • PEP-3156 EventLoop implementation using pyuv • pyuv.Poll: high performance level triggered I/O (works on Windows as well!) • Uses fairy dust covered unicorns • https://github.com/saghul/rose
  • 29. import rose import signal from rose import events, protocols class EchoProtocol(protocols.Protocol): def connection_made(self, transport): # TODO: Transport should probably expose getsockname/getpeername print("Client connected: {}".format(transport._sock.getpeername())) self.transport = transport def data_received(self, data): self.transport.write(data.upper()) def eof_received(self): self.transport.close() def connection_lost(self, exc): print("Client closed connection") reactor = events.new_event_loop() events.set_event_loop(reactor) reactor.start_serving(EchoProtocol, '127.0.0.1', 1234) reactor.add_signal_handler(signal.SIGINT, reactor.stop) reactor.run()
  • 30.