SlideShare una empresa de Scribd logo
1 de 60
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
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])
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)
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;
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

Más contenido relacionado

La actualidad más candente

Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in GeckoChih-Hsuan Kuo
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayGiordano Scalzo
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone DevelopmentGiordano Scalzo
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispDamien Cassou
 
Something about Golang
Something about GolangSomething about Golang
Something about GolangAnton Arhipov
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Chih-Hsuan Kuo
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in RustChih-Hsuan Kuo
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistAnton Arhipov
 
RuntimeUnitTestToolkit for Unity(English)
RuntimeUnitTestToolkit for Unity(English)RuntimeUnitTestToolkit for Unity(English)
RuntimeUnitTestToolkit for Unity(English)Yoshifumi Kawai
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistAnton Arhipov
 
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...Tsundere Chen
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Yoshifumi Kawai
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistAnton Arhipov
 
разработка серверов и серверных приложений лекция №4
разработка серверов и серверных приложений лекция №4разработка серверов и серверных приложений лекция №4
разработка серверов и серверных приложений лекция №4Eugeniy Tyumentcev
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopSaša Tatar
 
Python Yield
Python YieldPython Yield
Python Yieldyangjuven
 

La actualidad más candente (20)

Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp way
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
 
Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
 
RuntimeUnitTestToolkit for Unity(English)
RuntimeUnitTestToolkit for Unity(English)RuntimeUnitTestToolkit for Unity(English)
RuntimeUnitTestToolkit for Unity(English)
 
JAVA NIO
JAVA NIOJAVA NIO
JAVA NIO
 
Don't do this
Don't do thisDon't do this
Don't do this
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with Javassist
 
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
 
Cooking pies with Celery
Cooking pies with CeleryCooking pies with Celery
Cooking pies with Celery
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
 
разработка серверов и серверных приложений лекция №4
разработка серверов и серверных приложений лекция №4разработка серверов и серверных приложений лекция №4
разработка серверов и серверных приложений лекция №4
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Python Yield
Python YieldPython Yield
Python Yield
 

Similar a Gevent what's the point

Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBemptysquare
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+ConFoo
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterSimen Li
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212Mahmoud Samir Fayed
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 

Similar a Gevent what's the point (20)

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

Último

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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
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
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
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
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 

Último (20)

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, ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 

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
  • 24.
  • 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])
  • 31.
  • 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)
  • 36.
  • 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;
  • 51.
  • 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

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n