SlideShare a Scribd company logo
Gevent
What’s the point?
       Sean McQuillan
    sean@bittorrent.com
Bottom Line

Gevent is fast (libev)
Pythonic style
Single threaded event loop
Gevent is Fast
        application code

            gevent

libev                  greenlet

            kernel
Pythonic Style
def get_db():
    return db.query(...)
            vs
def _db_cb(result):
    consumer.send(result)

def get_db():
    x = db.query(...)
    x.addCallback(_db_cb)
Single Threaded
     Event Loop

Single threaded
Single Threaded
     Event Loop

Single threaded
 wait
Single Threaded
     Event Loop

Single threaded
 wait
 what?
Execution Model

One OS thread
Only ONE thing happens at a time...
 Switching constantly
More Execution Model

def example_function(sock):
    r = sock.recv(4096)
    count = len(r)
    for c in xrange(count):
       tokenizer.send(c)
    r += sock.recv(4096)
More Execution Model

def example_function(sock):
    r = sock.recv(4096)
    count = len(r)
    for c in xrange(count):
       tokenizer.send(c)
    r += sock.recv(4096)
More Execution Model


 def get_db():
     return db.query(...)
More Execution Model


 def get_db():
     return db.query(...)
Basic Example
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    import time; time.sleep(1)
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
from flask import Flask
app = Flask(__name__)

import gevent.monkey
gevent.monkey.patch_all()

@app.route('/')
def hello_world():
    import time; time.sleep(1)
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    import time; time.sleep(1)
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
from flask import Flask
app = Flask(__name__)
from flask import Flask
app = Flask(__name__)

import gevent.monkey
gevent.monkey.patch_all()

@app.route('/')
def hello_world():
    import time; time.sleep(1)
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
from flask import Flask
app = Flask(__name__)

import gevent.monkey
gevent.monkey.patch_all()
Interlude:
Monkey Patching
Monkey Patching


Replace existing libraries
Not generally done in python
Monkey Patching

sys.modules[socket] = gevent.socket
sys.modules[time] = gevent.sleep
...
Part II: Event Loops

Low overhead
Single threaded
Handle LOTS of connections
Gevent what's the point
poll, select, epoll, kqueue


 “Given a list of file descriptors which are
 ready for read or write.”
Lets dig in
        application code

            gevent

libev                  greenlet

            kernel
Lets dig in
socket 1 write callback   event      socket 1 read callback
socket 2 write callback    loop      socket 2 read callback


               socket 1, socket 2, ...

                          kernel
  write buffer 1                   read buffer 1
  write buffer 2                   read buffer 2
Example

Contrived event loop example
See t wisted event loop for real example
t wisted/interent/selectreactor.py
Example
rlist = []
wlist = []
callbacks = {}
pending = defaultdict(str)

def want_to_read(sock, cb):
    callbacks[sock.fileno] = cb
    global rlist
    rlist = list(set(rlist + [sock.fileno]))

def want_to_write(sock, data):
    pending[sock.fileno] += data
    global wlist
    wlist = list(set(wlist + [sock.fileno])))
Example

def event_loop():
    while True:
        reads, writes, _ = select(rlist, wlist, [])
        for readfd in reads:
            data = _do_actual_read(readfd)
            callbacks[readfd](data)
        for writefd in writes:
            _do_actual_write(pending[writefd])
Gevent what's the point
Part III: Sockets


Sockets
What magic lies here
patched socket.recv
def recv(self, *args):
    sock = self._sock
    while True:
        try:
             return sock.recv(*args)
        except error:
             ex = sys.exc_info()[1]
             if ex.args[0] == EBADF:
                 return ''
             if (ex.args[0] != EWOULDBLOCK or
                 self.timeout == 0.0 ):
                 raise
        self._wait(self._read_event)
patched socket.recv
def recv(self, *args):
    sock = self._sock
    while True:
        try:
             return sock.recv(*args)
        except error:
             ex = sys.exc_info()[1]
             if ex.args[0] == EBADF:
                 return ''
             if (ex.args[0] != EWOULDBLOCK or
                 self.timeout == 0.0 ):
                 raise
        self._wait(self._read_event)
patched socket.recv
def recv(self, *args):
    sock = self._sock
    while True:
        try:
             return sock.recv(*args)
        except error:
             ex = sys.exc_info()[1]
             if ex.args[0] == EBADF:
                 return ''
             if (ex.args[0] != EWOULDBLOCK or
                 self.timeout == 0.0 ):
                 raise
        self.want_to_read(sock,
             self.mygreenthread.switch)
Gevent what's the point
Part IV: Greenlets


“green” threads
Part IV: Greenlets


“green” threads
(that means fake threads)
Part IV: Greenlets


“green” threads
(that means fake threads)
Green Threads Good

Never switch accidentally
Never spend time blocked on IO
High performance switching
Green Threads Bad


Never preemptively interrupt
No SMP
Green Thread Execution




     Python Initial Stack
Green Thread Execution




      Gevent Initialized

     Python Initial Stack
Green Thread Execution


Green
Thread
 Stack

          Gevent Initialized

         Python Initial Stack
Green Thread Execution
               Green
               Thread
Green           Stack
Thread
 Stack

          Gevent Initialized

         Python Initial Stack
Green Thread Execution
                Green
                Thread
Green            Stack
Thread
 Stack

          Gevent Initialized

         Python Initial Stack
Green Thread Execution
                Green Green
                Thread Thread
Green            Stack Stack
Thread
 Stack

          Gevent Initialized

         Python Initial Stack
Green Thread Execution
                Green     Green
                Thread    Thread
Green            Stack     Stack
Thread
 Stack

          Gevent Initialized

         Python Initial Stack
Green Thread Execution
                Green     Green
                Thread    Thread
Green            Stack     Stack
Thread
 Stack

          Gevent Initialized

         Python Initial Stack
How does it switch?
  (x86 assembly)
    void *ebp, *ebx;
    unsigned short cw;
    register int *stackref, stsizediff;
    __asm__ volatile ("" : : : "esi", "edi");
    __asm__ volatile ("fstcw %0" : "=m" (cw));
    __asm__ volatile ("movl %%ebp, %0" : "=m" (ebp));
    __asm__ volatile ("movl %%ebx, %0" : "=m" (ebx));
    __asm__ ("movl %%esp, %0" : "=g" (stackref));
    {
        SLP_SAVE_STATE(stackref, stsizediff);
        __asm__ volatile (
            "addl %0, %%espn"
            "addl %0, %%ebpn"
            :
            : "r" (stsizediff)
            );
        SLP_RESTORE_STATE();
    }
    __asm__ volatile ("movl %0, %%ebx" : : "m" (ebx));
    __asm__ volatile ("movl %0, %%ebp" : : "m" (ebp));
    __asm__ volatile ("fldcw %0" : : "m" (cw));
    __asm__ volatile ("" : : : "esi", "edi");
    return 0;
Gevent what's the point
When to use Gevent

Replace thread-based ser vers
Replace thread-based clients
Lighter than multiprocessing
When not to use gevent

 When SMP is required
 High CPU load
 Latency guarntees
 Memory star ved systems
Twisted
Mature, async-baked, implementations
of most protocols
 DNS Ser ver
 SSH Server
 AWS
 AMQP
 Web
Tornado

HTTP
Highly performant
Less protocol / library support



                            I’m not an expert
Erlang

Scales more vertically (dozens of cores)
Similar execution model
Less library support
Python Threading


I’ve never tried to write a “web-scale”
server with it, would love to hear your
experience
Python
  Multiproccessing


Great SMP usage
Go


Never used, benchmarks look good
The End

More Related Content

PPTX
Artificial Intelligence- TicTacToe game
PPT
Introduction to Data Oriented Design
PPTX
weak slot and filler structure
PPT
Directory services by SAJID
PPTX
Pentesting ntp-17-02-18
PPT
Artificial Intelligence - Reasoning in Uncertain Situations
PDF
Ch 7 Knowledge Representation.pdf
PPTX
Maze Problem Presentation
Artificial Intelligence- TicTacToe game
Introduction to Data Oriented Design
weak slot and filler structure
Directory services by SAJID
Pentesting ntp-17-02-18
Artificial Intelligence - Reasoning in Uncertain Situations
Ch 7 Knowledge Representation.pdf
Maze Problem Presentation

What's hot (20)

PDF
Perspective in Informatics 3 - Assignment 2 - Answer Sheet
PPTX
Introduction to Prolog
PPTX
Data decomposition techniques
PPTX
Backtracking
PPTX
Case Study - SUN NFS
PDF
File System Modules
PDF
I.ITERATIVE DEEPENING DEPTH FIRST SEARCH(ID-DFS) II.INFORMED SEARCH IN ARTIFI...
PPT
Knowledge engg using & in fol
PPT
01 knapsack using backtracking
PPTX
Asymptotic notations(Big O, Omega, Theta )
PDF
Optical character recognition of handwritten Arabic using hidden Markov models
PPTX
5.problem reduction in artificial intelligence.pptx
PPTX
Java media framework
PPTX
tic-tac-toe: Game playing
PDF
Full solution manual real time system by jane w s liu solution manual
PPTX
Resolution method in AI.pptx
PPT
Ch2 3-informed (heuristic) search
PDF
Building Responsive Applications Using XPages
PPTX
deadlock handling
PPTX
Planning in AI(Partial order planning)
Perspective in Informatics 3 - Assignment 2 - Answer Sheet
Introduction to Prolog
Data decomposition techniques
Backtracking
Case Study - SUN NFS
File System Modules
I.ITERATIVE DEEPENING DEPTH FIRST SEARCH(ID-DFS) II.INFORMED SEARCH IN ARTIFI...
Knowledge engg using & in fol
01 knapsack using backtracking
Asymptotic notations(Big O, Omega, Theta )
Optical character recognition of handwritten Arabic using hidden Markov models
5.problem reduction in artificial intelligence.pptx
Java media framework
tic-tac-toe: Game playing
Full solution manual real time system by jane w s liu solution manual
Resolution method in AI.pptx
Ch2 3-informed (heuristic) search
Building Responsive Applications Using XPages
deadlock handling
Planning in AI(Partial order planning)
Ad

Similar to Gevent what's the point (20)

PPTX
Python, async web frameworks, and MongoDB
PDF
What can be done with Java, but should better be done with Erlang (@pavlobaron)
PDF
Java 7 LavaJUG
PDF
Python magicmethods
PDF
Scala coated JVM
PDF
Java 7 at SoftShake 2011
PDF
Java 7 JUG Summer Camp
PDF
JAVA SE 7
PDF
Coding in Style
PDF
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
PDF
Node.js Event Loop & EventEmitter
PDF
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
PPTX
Node.js System: The Landing
PDF
Writing Faster Python 3
PDF
Silicon Valley JUG: JVM Mechanics
PDF
The Ring programming language version 1.10 book - Part 94 of 212
PDF
обзор Python
PDF
CoffeeScript
PPTX
Gevent rabbit rpc
PDF
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
Python, async web frameworks, and MongoDB
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Java 7 LavaJUG
Python magicmethods
Scala coated JVM
Java 7 at SoftShake 2011
Java 7 JUG Summer Camp
JAVA SE 7
Coding in Style
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Node.js Event Loop & EventEmitter
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Node.js System: The Landing
Writing Faster Python 3
Silicon Valley JUG: JVM Mechanics
The Ring programming language version 1.10 book - Part 94 of 212
обзор Python
CoffeeScript
Gevent rabbit rpc
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
Ad

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Empathic Computing: Creating Shared Understanding
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
cuic standard and advanced reporting.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
Big Data Technologies - Introduction.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
KodekX | Application Modernization Development
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Cloud computing and distributed systems.
PDF
Electronic commerce courselecture one. Pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
MYSQL Presentation for SQL database connectivity
Network Security Unit 5.pdf for BCA BBA.
Dropbox Q2 2025 Financial Results & Investor Presentation
Advanced methodologies resolving dimensionality complications for autism neur...
Empathic Computing: Creating Shared Understanding
Unlocking AI with Model Context Protocol (MCP)
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Review of recent advances in non-invasive hemoglobin estimation
cuic standard and advanced reporting.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Big Data Technologies - Introduction.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
KodekX | Application Modernization Development
20250228 LYD VKU AI Blended-Learning.pptx
Cloud computing and distributed systems.
Electronic commerce courselecture one. Pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Digital-Transformation-Roadmap-for-Companies.pptx

Gevent what's the point

  • 1. Gevent What’s the point? Sean McQuillan sean@bittorrent.com
  • 2. Bottom Line Gevent is fast (libev) Pythonic style Single threaded event loop
  • 3. Gevent is Fast application code gevent libev greenlet kernel
  • 4. Pythonic Style def get_db(): return db.query(...) vs def _db_cb(result): consumer.send(result) def get_db(): x = db.query(...) x.addCallback(_db_cb)
  • 5. Single Threaded Event Loop Single threaded
  • 6. Single Threaded Event Loop Single threaded wait
  • 7. Single Threaded Event Loop Single threaded wait what?
  • 8. Execution Model One OS thread Only ONE thing happens at a time... Switching constantly
  • 9. More Execution Model def example_function(sock): r = sock.recv(4096) count = len(r) for c in xrange(count): tokenizer.send(c) r += sock.recv(4096)
  • 10. More Execution Model def example_function(sock): r = sock.recv(4096) count = len(r) for c in xrange(count): tokenizer.send(c) r += sock.recv(4096)
  • 11. More Execution Model def get_db(): return db.query(...)
  • 12. More Execution Model def get_db(): return db.query(...)
  • 14. from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): import time; time.sleep(1) return 'Hello World!' if __name__ == '__main__': app.run()
  • 15. from flask import Flask app = Flask(__name__) import gevent.monkey gevent.monkey.patch_all() @app.route('/') def hello_world(): import time; time.sleep(1) return 'Hello World!' if __name__ == '__main__': app.run()
  • 16. from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): import time; time.sleep(1) return 'Hello World!' if __name__ == '__main__': app.run()
  • 17. from flask import Flask app = Flask(__name__)
  • 18. from flask import Flask app = Flask(__name__) import gevent.monkey gevent.monkey.patch_all() @app.route('/') def hello_world(): import time; time.sleep(1) return 'Hello World!' if __name__ == '__main__': app.run()
  • 19. from flask import Flask app = Flask(__name__) import gevent.monkey gevent.monkey.patch_all()
  • 21. Monkey Patching Replace existing libraries Not generally done in python
  • 22. Monkey Patching sys.modules[socket] = gevent.socket sys.modules[time] = gevent.sleep ...
  • 23. Part II: Event Loops Low overhead Single threaded Handle LOTS of connections
  • 25. poll, select, epoll, kqueue “Given a list of file descriptors which are ready for read or write.”
  • 26. Lets dig in application code gevent libev greenlet kernel
  • 27. Lets dig in socket 1 write callback event socket 1 read callback socket 2 write callback loop socket 2 read callback socket 1, socket 2, ... kernel write buffer 1 read buffer 1 write buffer 2 read buffer 2
  • 28. Example Contrived event loop example See t wisted event loop for real example t wisted/interent/selectreactor.py
  • 29. Example rlist = [] wlist = [] callbacks = {} pending = defaultdict(str) def want_to_read(sock, cb): callbacks[sock.fileno] = cb global rlist rlist = list(set(rlist + [sock.fileno])) def want_to_write(sock, data): pending[sock.fileno] += data global wlist wlist = list(set(wlist + [sock.fileno])))
  • 30. Example def event_loop(): while True: reads, writes, _ = select(rlist, wlist, []) for readfd in reads: data = _do_actual_read(readfd) callbacks[readfd](data) for writefd in writes: _do_actual_write(pending[writefd])
  • 33. patched socket.recv def recv(self, *args): sock = self._sock while True: try: return sock.recv(*args) except error: ex = sys.exc_info()[1] if ex.args[0] == EBADF: return '' if (ex.args[0] != EWOULDBLOCK or self.timeout == 0.0 ): raise self._wait(self._read_event)
  • 34. patched socket.recv def recv(self, *args): sock = self._sock while True: try: return sock.recv(*args) except error: ex = sys.exc_info()[1] if ex.args[0] == EBADF: return '' if (ex.args[0] != EWOULDBLOCK or self.timeout == 0.0 ): raise self._wait(self._read_event)
  • 35. patched socket.recv def recv(self, *args): sock = self._sock while True: try: return sock.recv(*args) except error: ex = sys.exc_info()[1] if ex.args[0] == EBADF: return '' if (ex.args[0] != EWOULDBLOCK or self.timeout == 0.0 ): raise self.want_to_read(sock, self.mygreenthread.switch)
  • 38. Part IV: Greenlets “green” threads (that means fake threads)
  • 39. Part IV: Greenlets “green” threads (that means fake threads)
  • 40. Green Threads Good Never switch accidentally Never spend time blocked on IO High performance switching
  • 41. Green Threads Bad Never preemptively interrupt No SMP
  • 42. Green Thread Execution Python Initial Stack
  • 43. Green Thread Execution Gevent Initialized Python Initial Stack
  • 44. Green Thread Execution Green Thread Stack Gevent Initialized Python Initial Stack
  • 45. Green Thread Execution Green Thread Green Stack Thread Stack Gevent Initialized Python Initial Stack
  • 46. Green Thread Execution Green Thread Green Stack Thread Stack Gevent Initialized Python Initial Stack
  • 47. Green Thread Execution Green Green Thread Thread Green Stack Stack Thread Stack Gevent Initialized Python Initial Stack
  • 48. Green Thread Execution Green Green Thread Thread Green Stack Stack Thread Stack Gevent Initialized Python Initial Stack
  • 49. Green Thread Execution Green Green Thread Thread Green Stack Stack Thread Stack Gevent Initialized Python Initial Stack
  • 50. How does it switch? (x86 assembly)     void *ebp, *ebx;     unsigned short cw;     register int *stackref, stsizediff;     __asm__ volatile ("" : : : "esi", "edi");     __asm__ volatile ("fstcw %0" : "=m" (cw));     __asm__ volatile ("movl %%ebp, %0" : "=m" (ebp));     __asm__ volatile ("movl %%ebx, %0" : "=m" (ebx));     __asm__ ("movl %%esp, %0" : "=g" (stackref));     {         SLP_SAVE_STATE(stackref, stsizediff);         __asm__ volatile (             "addl %0, %%espn"             "addl %0, %%ebpn"             :             : "r" (stsizediff)             );         SLP_RESTORE_STATE();     }     __asm__ volatile ("movl %0, %%ebx" : : "m" (ebx));     __asm__ volatile ("movl %0, %%ebp" : : "m" (ebp));     __asm__ volatile ("fldcw %0" : : "m" (cw));     __asm__ volatile ("" : : : "esi", "edi");     return 0;
  • 52. When to use Gevent Replace thread-based ser vers Replace thread-based clients Lighter than multiprocessing
  • 53. When not to use gevent When SMP is required High CPU load Latency guarntees Memory star ved systems
  • 54. Twisted Mature, async-baked, implementations of most protocols DNS Ser ver SSH Server AWS AMQP Web
  • 55. Tornado HTTP Highly performant Less protocol / library support I’m not an expert
  • 56. Erlang Scales more vertically (dozens of cores) Similar execution model Less library support
  • 57. Python Threading I’ve never tried to write a “web-scale” server with it, would love to hear your experience

Editor's Notes