SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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
 

What's hot (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 to 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 to 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
 

Recently uploaded

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Recently uploaded (20)

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

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

Editor's Notes

  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