SlideShare uma empresa Scribd logo
1 de 24
Baixar para ler offline
Understanding greenlet
Saúl Ibarra Corretgé - @saghul
Amsterdam Python Meetup Group
Quick check
Gevent or Eventlet, anyone?
Who knows what greenlet is?
Who has used it (standalone)?
Who understands how it works?
Greenlet
Micro-threads with no implicit scheduling
Lightweight
Only one can run at a time
Cooperative
Greenlet API
greenlet(func, parent=None): creates a greenlet to
run ‘func’
greenlet.switch(*args, **kw): switches execution to
the target greenlet, the first time
func(*args, **kw) will be executed
greenlet.throw([typ, [val, [tb]]]): switches execution
to the target greenlet and raises the specified
exception (GreenletExit by default)
Example
import greenlet

main = greenlet.getcurrent()
def foo(n):
main.switch(n)
def bar(n):
foo(n)
return 'hello'

g1 = greenlet.greenlet(bar)
print g1.switch(42) # 42
print g1.switch()
# 'hello'
print g1.dead
# True
How does it work?
Organized in a tree structure
Each greenlet has a ‘parent’, except main
When a greenlet dies, control is switched to its parent

Execution order isn’t always obvious
A glorified GOTO?!
How does it work? (II)
greenlet2
greenlet1
greenlet3
greenlet5
greenlet4
How does it work? (III)
‘Stack switching’
Non portable asm code
Copy stack slices on the heap

State is saved and restored when switching
CPU registers
Current Python frame, recursion depth and exception
state
Enter PyPy
New shiny and fast implementation of Python
Vast amount of fairy-dust covered unicorns
included
Includes an implementation of greenlet
Implemented on top of “continulet” objects
import _continuation
Continulets are one-shot continuations
Switching code is a standalone C library: stacklet
rpython/translator/c/src/stacklet/
Continulet API
continulet(func, *args, **kw): create a continulet
object which will call fun(cont, *args, **kw)
continulet.switch(value=None, to=None): start the
continulet or activate the previously suspended
one. If to is specified a ‘double switch’ is
performed
continulet.throw(type, value=None, tb=None,
to=None): similar to switch, but raise the given
exception after the switch is done
Stacklet
Tiny library implementing one-shot continuations
for C
Single C file (~400 lines) + per-platform asm

Supports x86, x86_64 and ARM
Nice and simple API
Stacklet API
stacklet_newthread(): creates a new thread handle
stacklet_new(thread_handle, run_func, run_arg):
calls run(arg) in a new stacklet, starts immediately
stacklet_switch(target): switches execution to
target stacklet
#include <assert.h>
#include "stacklet.h"

Example

static stacklet_thread_handle thrd;

stacklet_handle empty_callback(stacklet_handle h, void *arg)
{
assert(arg == (void *)123);
return h;
}
void test_new(void)
{
stacklet_handle h = stacklet_new(thrd, empty_callback, (void *)123);
assert(h == EMPTY_STACKLET_HANDLE);
}

int main(int argc, char **argv)
{
thrd = stacklet_newthread();
test_new();
stacklet_deletethread(thrd);
return 0;
}
The Stacklet Sandwich (TM)
greenlet

continulet

stacklet
Using greenlet
Too low level, it’s usually used through a
framework
gevent, eventlet, evergreen *, gruvi *, ...
In these frameworks, switching happens through a
“hub”

*: these frameworks use python-fibers now
Using greenlet (II)
main

g1

hub

g2

g3

...
Undoing callbacks
import greenlet

# ...
def foo_async(cb):
call cb(result, error) eventually
pass
def foo_sync():
current = greenlet.getcurrent()
def cb(result, error):
if error is not None:
current.throw(Exception(error))
else:
current.switch(result)
foo_async(cb)
return hub.switch()
import fibers

shameless
plug!

Micro-threadling library API inspired by Python
threads and greenlet
Uses stacklet underneath

Works on CPython and PyPy
On PyPy it uses continulets

github.com/saghul/python-fibers
Or pip install fibers
Questions?

@saghul
bettercallsaghul.com

Mais conteúdo relacionado

Mais procurados

Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
Kernel TLV
 

Mais procurados (20)

DPDK in Containers Hands-on Lab
DPDK in Containers Hands-on LabDPDK in Containers Hands-on Lab
DPDK in Containers Hands-on Lab
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
 
Using GTP on Linux with libgtpnl
Using GTP on Linux with libgtpnlUsing GTP on Linux with libgtpnl
Using GTP on Linux with libgtpnl
 
Introduction to Git / Github
Introduction to Git / GithubIntroduction to Git / Github
Introduction to Git / Github
 
Building a fully managed stream processing platform on Flink at scale for Lin...
Building a fully managed stream processing platform on Flink at scale for Lin...Building a fully managed stream processing platform on Flink at scale for Lin...
Building a fully managed stream processing platform on Flink at scale for Lin...
 
Linux 4.x Tracing: Performance Analysis with bcc/BPF
Linux 4.x Tracing: Performance Analysis with bcc/BPFLinux 4.x Tracing: Performance Analysis with bcc/BPF
Linux 4.x Tracing: Performance Analysis with bcc/BPF
 
Introduction to eBPF and XDP
Introduction to eBPF and XDPIntroduction to eBPF and XDP
Introduction to eBPF and XDP
 
Awesome Traefik - Ingress Controller for Kubernetes - Swapnasagar Pradhan
Awesome Traefik - Ingress Controller for Kubernetes - Swapnasagar PradhanAwesome Traefik - Ingress Controller for Kubernetes - Swapnasagar Pradhan
Awesome Traefik - Ingress Controller for Kubernetes - Swapnasagar Pradhan
 
ebpf and IO Visor: The What, how, and what next!
ebpf and IO Visor: The What, how, and what next!ebpf and IO Visor: The What, how, and what next!
ebpf and IO Visor: The What, how, and what next!
 
UM2019 Extended BPF: A New Type of Software
UM2019 Extended BPF: A New Type of SoftwareUM2019 Extended BPF: A New Type of Software
UM2019 Extended BPF: A New Type of Software
 
Git and git flow
Git and git flowGit and git flow
Git and git flow
 
Mininet multiple controller
Mininet   multiple controllerMininet   multiple controller
Mininet multiple controller
 
Open vSwitch - Stateful Connection Tracking & Stateful NAT
Open vSwitch - Stateful Connection Tracking & Stateful NATOpen vSwitch - Stateful Connection Tracking & Stateful NAT
Open vSwitch - Stateful Connection Tracking & Stateful NAT
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at Netflix
 
PyTorch Tutorial for NTU Machine Learing Course 2017
PyTorch Tutorial for NTU Machine Learing Course 2017PyTorch Tutorial for NTU Machine Learing Course 2017
PyTorch Tutorial for NTU Machine Learing Course 2017
 
Tutorial: Using GoBGP as an IXP connecting router
Tutorial: Using GoBGP as an IXP connecting routerTutorial: Using GoBGP as an IXP connecting router
Tutorial: Using GoBGP as an IXP connecting router
 
Monitoring Kafka without instrumentation using eBPF with Antón Rodríguez | Ka...
Monitoring Kafka without instrumentation using eBPF with Antón Rodríguez | Ka...Monitoring Kafka without instrumentation using eBPF with Antón Rodríguez | Ka...
Monitoring Kafka without instrumentation using eBPF with Antón Rodríguez | Ka...
 
OpenTelemetry For Architects
OpenTelemetry For ArchitectsOpenTelemetry For Architects
OpenTelemetry For Architects
 
Git - An Introduction
Git - An IntroductionGit - An Introduction
Git - An Introduction
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in Rust
 

Destaque

Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with gevent
Mahendra M
 
The new masters of management
The new masters of managementThe new masters of management
The new masters of management
rsoosaar
 
Formula of failure and success
Formula of failure and successFormula of failure and success
Formula of failure and success
Ujjwal Panda
 

Destaque (20)

Python Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and GeventPython Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and Gevent
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with gevent
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django Architecture
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Python Performance Profiling: The Guts And The Glory
Python Performance Profiling: The Guts And The GloryPython Performance Profiling: The Guts And The Glory
Python Performance Profiling: The Guts And The Glory
 
Разработка сетевых приложений с gevent
Разработка сетевых приложений с geventРазработка сетевых приложений с gevent
Разработка сетевых приложений с gevent
 
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
 
Django channels
Django channelsDjango channels
Django channels
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame Graphs
 
The new masters of management
The new masters of managementThe new masters of management
The new masters of management
 
Rooman Proposal
Rooman ProposalRooman Proposal
Rooman Proposal
 
Modul 5 kb 1
Modul 5   kb 1Modul 5   kb 1
Modul 5 kb 1
 
Ciclo basico diurno vigencia 2009 scp
Ciclo basico diurno vigencia 2009 scpCiclo basico diurno vigencia 2009 scp
Ciclo basico diurno vigencia 2009 scp
 
Introduction to Ext JS 4
Introduction to Ext JS 4Introduction to Ext JS 4
Introduction to Ext JS 4
 
user: Roo-user-Ob-PicklistMulti-Value-minimal uploder
  user: Roo-user-Ob-PicklistMulti-Value-minimal uploder  user: Roo-user-Ob-PicklistMulti-Value-minimal uploder
user: Roo-user-Ob-PicklistMulti-Value-minimal uploder
 
Formula of failure and success
Formula of failure and successFormula of failure and success
Formula of failure and success
 
article198
article198article198
article198
 
PHP Apps on the Move - Migrating from In-House to Cloud
PHP Apps on the Move - Migrating from In-House to Cloud  PHP Apps on the Move - Migrating from In-House to Cloud
PHP Apps on the Move - Migrating from In-House to Cloud
 
Rxpay-sepa-germany-01
Rxpay-sepa-germany-01Rxpay-sepa-germany-01
Rxpay-sepa-germany-01
 
The Anatomy Of The Idea
The Anatomy Of The IdeaThe Anatomy Of The Idea
The Anatomy Of The Idea
 

Semelhante a Understanding greenlet

Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
Devnology
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
seanmcq
 
Concurrent talk
Concurrent talkConcurrent talk
Concurrent talk
rahulrevo
 
Unit 4
Unit 4Unit 4
Unit 4
siddr
 
package algs13;import stdlib.;import java.util.Iterator;im.docx
package algs13;import  stdlib.;import java.util.Iterator;im.docxpackage algs13;import  stdlib.;import java.util.Iterator;im.docx
package algs13;import stdlib.;import java.util.Iterator;im.docx
gerardkortney
 
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxIn Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
bradburgess22840
 

Semelhante a Understanding greenlet (20)

Stack switching for fun and profit
Stack switching for fun and profitStack switching for fun and profit
Stack switching for fun and profit
 
Thread
ThreadThread
Thread
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Lockless
LocklessLockless
Lockless
 
Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approach
 
Concurrent talk
Concurrent talkConcurrent talk
Concurrent talk
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and Iterations
 
Stackless Python 101
Stackless Python 101Stackless Python 101
Stackless Python 101
 
Unit 4
Unit 4Unit 4
Unit 4
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
package algs13;import stdlib.;import java.util.Iterator;im.docx
package algs13;import  stdlib.;import java.util.Iterator;im.docxpackage algs13;import  stdlib.;import java.util.Iterator;im.docx
package algs13;import stdlib.;import java.util.Iterator;im.docx
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's Tricks
 
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxIn Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
 
Effective java item 80 and 81
Effective java   item 80 and 81Effective java   item 80 and 81
Effective java item 80 and 81
 

Mais de Saúl Ibarra Corretgé

Mais de Saúl Ibarra Corretgé (20)

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

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 

Understanding greenlet

  • 1. Understanding greenlet Saúl Ibarra Corretgé - @saghul Amsterdam Python Meetup Group
  • 2. Quick check Gevent or Eventlet, anyone? Who knows what greenlet is? Who has used it (standalone)? Who understands how it works?
  • 3. Greenlet Micro-threads with no implicit scheduling Lightweight Only one can run at a time Cooperative
  • 4. Greenlet API greenlet(func, parent=None): creates a greenlet to run ‘func’ greenlet.switch(*args, **kw): switches execution to the target greenlet, the first time func(*args, **kw) will be executed greenlet.throw([typ, [val, [tb]]]): switches execution to the target greenlet and raises the specified exception (GreenletExit by default)
  • 5. Example import greenlet main = greenlet.getcurrent() def foo(n): main.switch(n) def bar(n): foo(n) return 'hello' g1 = greenlet.greenlet(bar) print g1.switch(42) # 42 print g1.switch() # 'hello' print g1.dead # True
  • 6. How does it work? Organized in a tree structure Each greenlet has a ‘parent’, except main When a greenlet dies, control is switched to its parent Execution order isn’t always obvious A glorified GOTO?!
  • 7. How does it work? (II) greenlet2 greenlet1 greenlet3 greenlet5 greenlet4
  • 8. How does it work? (III) ‘Stack switching’ Non portable asm code Copy stack slices on the heap State is saved and restored when switching CPU registers Current Python frame, recursion depth and exception state
  • 9.
  • 10.
  • 11.
  • 12.
  • 13. Enter PyPy New shiny and fast implementation of Python Vast amount of fairy-dust covered unicorns included Includes an implementation of greenlet Implemented on top of “continulet” objects
  • 14. import _continuation Continulets are one-shot continuations Switching code is a standalone C library: stacklet rpython/translator/c/src/stacklet/
  • 15. Continulet API continulet(func, *args, **kw): create a continulet object which will call fun(cont, *args, **kw) continulet.switch(value=None, to=None): start the continulet or activate the previously suspended one. If to is specified a ‘double switch’ is performed continulet.throw(type, value=None, tb=None, to=None): similar to switch, but raise the given exception after the switch is done
  • 16. Stacklet Tiny library implementing one-shot continuations for C Single C file (~400 lines) + per-platform asm Supports x86, x86_64 and ARM Nice and simple API
  • 17. Stacklet API stacklet_newthread(): creates a new thread handle stacklet_new(thread_handle, run_func, run_arg): calls run(arg) in a new stacklet, starts immediately stacklet_switch(target): switches execution to target stacklet
  • 18. #include <assert.h> #include "stacklet.h" Example static stacklet_thread_handle thrd; stacklet_handle empty_callback(stacklet_handle h, void *arg) { assert(arg == (void *)123); return h; } void test_new(void) { stacklet_handle h = stacklet_new(thrd, empty_callback, (void *)123); assert(h == EMPTY_STACKLET_HANDLE); } int main(int argc, char **argv) { thrd = stacklet_newthread(); test_new(); stacklet_deletethread(thrd); return 0; }
  • 19. The Stacklet Sandwich (TM) greenlet continulet stacklet
  • 20. Using greenlet Too low level, it’s usually used through a framework gevent, eventlet, evergreen *, gruvi *, ... In these frameworks, switching happens through a “hub” *: these frameworks use python-fibers now
  • 22. Undoing callbacks import greenlet # ... def foo_async(cb): call cb(result, error) eventually pass def foo_sync(): current = greenlet.getcurrent() def cb(result, error): if error is not None: current.throw(Exception(error)) else: current.switch(result) foo_async(cb) return hub.switch()
  • 23. import fibers shameless plug! Micro-threadling library API inspired by Python threads and greenlet Uses stacklet underneath Works on CPython and PyPy On PyPy it uses continulets github.com/saghul/python-fibers Or pip install fibers