SlideShare una empresa de Scribd logo
1 de 24
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

A visual introduction to Apache Kafka
A visual introduction to Apache KafkaA visual introduction to Apache Kafka
A visual introduction to Apache KafkaPaul Brebner
 
Asynchronous Programming at Netflix
Asynchronous Programming at NetflixAsynchronous Programming at Netflix
Asynchronous Programming at NetflixC4Media
 
Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra...
 Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra... Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra...
Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra...HostedbyConfluent
 
Introduction to Vacuum Freezing and XID
Introduction to Vacuum Freezing and XIDIntroduction to Vacuum Freezing and XID
Introduction to Vacuum Freezing and XIDPGConf APAC
 
Increasing Kafka Connect Throughput with Catalin Pop with Catalin Pop | Kafka...
Increasing Kafka Connect Throughput with Catalin Pop with Catalin Pop | Kafka...Increasing Kafka Connect Throughput with Catalin Pop with Catalin Pop | Kafka...
Increasing Kafka Connect Throughput with Catalin Pop with Catalin Pop | Kafka...HostedbyConfluent
 
스프링5 웹플럭스와 테스트 전략
스프링5 웹플럭스와 테스트 전략스프링5 웹플럭스와 테스트 전략
스프링5 웹플럭스와 테스트 전략if kakao
 
Kafka Connect & Streams - the ecosystem around Kafka
Kafka Connect & Streams - the ecosystem around KafkaKafka Connect & Streams - the ecosystem around Kafka
Kafka Connect & Streams - the ecosystem around KafkaGuido Schmutz
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldJorge Vásquez
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Mario Fusco
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with geventMahendra M
 
Apache Kafka from 0.7 to 1.0, History and Lesson Learned
Apache Kafka from 0.7 to 1.0, History and Lesson LearnedApache Kafka from 0.7 to 1.0, History and Lesson Learned
Apache Kafka from 0.7 to 1.0, History and Lesson LearnedGuozhang Wang
 

La actualidad más candente (20)

A visual introduction to Apache Kafka
A visual introduction to Apache KafkaA visual introduction to Apache Kafka
A visual introduction to Apache Kafka
 
Asynchronous Programming at Netflix
Asynchronous Programming at NetflixAsynchronous Programming at Netflix
Asynchronous Programming at Netflix
 
Kafka presentation
Kafka presentationKafka presentation
Kafka presentation
 
Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra...
 Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra... Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra...
Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra...
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
Row/Column- Level Security in SQL for Apache Spark
Row/Column- Level Security in SQL for Apache SparkRow/Column- Level Security in SQL for Apache Spark
Row/Column- Level Security in SQL for Apache Spark
 
Airflow and supervisor
Airflow and supervisorAirflow and supervisor
Airflow and supervisor
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Introduction to Vacuum Freezing and XID
Introduction to Vacuum Freezing and XIDIntroduction to Vacuum Freezing and XID
Introduction to Vacuum Freezing and XID
 
Increasing Kafka Connect Throughput with Catalin Pop with Catalin Pop | Kafka...
Increasing Kafka Connect Throughput with Catalin Pop with Catalin Pop | Kafka...Increasing Kafka Connect Throughput with Catalin Pop with Catalin Pop | Kafka...
Increasing Kafka Connect Throughput with Catalin Pop with Catalin Pop | Kafka...
 
스프링5 웹플럭스와 테스트 전략
스프링5 웹플럭스와 테스트 전략스프링5 웹플럭스와 테스트 전략
스프링5 웹플럭스와 테스트 전략
 
Apache Kafka at LinkedIn
Apache Kafka at LinkedInApache Kafka at LinkedIn
Apache Kafka at LinkedIn
 
Kafka Connect & Streams - the ecosystem around Kafka
Kafka Connect & Streams - the ecosystem around KafkaKafka Connect & Streams - the ecosystem around Kafka
Kafka Connect & Streams - the ecosystem around Kafka
 
kafka
kafkakafka
kafka
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with gevent
 
Apache Kafka from 0.7 to 1.0, History and Lesson Learned
Apache Kafka from 0.7 to 1.0, History and Lesson LearnedApache Kafka from 0.7 to 1.0, History and Lesson Learned
Apache Kafka from 0.7 to 1.0, History and Lesson Learned
 

Destacado

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 Geventemptysquare
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django ArchitectureRami Sayar
 
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 Gloryemptysquare
 
Разработка сетевых приложений с gevent
Разработка сетевых приложений с geventРазработка сетевых приложений с gevent
Разработка сетевых приложений с geventAndrey Popp
 
Django channels
Django channelsDjango channels
Django channelsAndy Dai
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBrendan Gregg
 
The new masters of management
The new masters of managementThe new masters of management
The new masters of managementrsoosaar
 
Rooman Proposal
Rooman ProposalRooman Proposal
Rooman ProposalPrasad Pai
 
Ciclo basico diurno vigencia 2009 scp
Ciclo basico diurno vigencia 2009 scpCiclo basico diurno vigencia 2009 scp
Ciclo basico diurno vigencia 2009 scpRuth Santana
 
Introduction to Ext JS 4
Introduction to Ext JS 4Introduction to Ext JS 4
Introduction to Ext JS 4Stefan Gehrig
 
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 uploderRoopa slideshare
 
Formula of failure and success
Formula of failure and successFormula of failure and success
Formula of failure and successUjjwal Panda
 
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 RightScale
 

Destacado (19)

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
 
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
 

Similar a Understanding greenlet

Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel GeheugenDevnology
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the pointseanmcq
 
Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approachAlexander Granin
 
Concurrent talk
Concurrent talkConcurrent talk
Concurrent talkrahulrevo
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and IterationsSameer Wadkar
 
Stackless Python 101
Stackless Python 101Stackless Python 101
Stackless Python 101guest162fd90
 
Unit 4
Unit 4Unit 4
Unit 4siddr
 
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++nsm.nikhil
 
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.docxgerardkortney
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio Zoppi
 
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 TricksDoug Hawkins
 
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.docxbradburgess22840
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstituteSuresh Loganatha
 
Effective java item 80 and 81
Effective java   item 80 and 81Effective java   item 80 and 81
Effective java item 80 and 81Isaac Liao
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 

Similar 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
 
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
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 

Más de Saúl Ibarra Corretgé

Challenges running Jitsi Meet at scale during the pandemic
Challenges running Jitsi Meet at scale during the pandemicChallenges running Jitsi Meet at scale during the pandemic
Challenges running Jitsi Meet at scale during the pandemicSaúl Ibarra Corretgé
 
The Road to End-to-End Encryption in Jitsi Meet
The Road to End-to-End Encryption in Jitsi MeetThe Road to End-to-End Encryption in Jitsi Meet
The Road to End-to-End Encryption in Jitsi MeetSaúl Ibarra Corretgé
 
Jitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: our tale of blood, sweat, tears and loveJitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: our tale of blood, sweat, tears and loveSaúl Ibarra Corretgé
 
Jitsi Meet: Video conferencing for the privacy minded
Jitsi Meet: Video conferencing for the privacy mindedJitsi Meet: Video conferencing for the privacy minded
Jitsi Meet: Video conferencing for the privacy mindedSaúl Ibarra Corretgé
 
Get a room! Spot: the ultimate physical meeting room experience
Get a room! Spot: the ultimate physical meeting room experienceGet a room! Spot: the ultimate physical meeting room experience
Get a room! Spot: the ultimate physical meeting room experienceSaúl Ibarra Corretgé
 
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCGoing Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCSaúl Ibarra Corretgé
 
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCGoing Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCSaúl Ibarra Corretgé
 
Jitsi: state-of-the-art video conferencing you can self-host
Jitsi: state-of-the-art video conferencing you can self-hostJitsi: state-of-the-art video conferencing you can self-host
Jitsi: state-of-the-art video conferencing you can self-hostSaúl Ibarra Corretgé
 
WebRTC: El epicentro de la videoconferencia y IoT
WebRTC: El epicentro de la videoconferencia y IoTWebRTC: El epicentro de la videoconferencia y IoT
WebRTC: El epicentro de la videoconferencia y IoTSaúl Ibarra Corretgé
 
libuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/olibuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/oSaúl Ibarra Corretgé
 
Videoconferencias: el santo grial de WebRTC
Videoconferencias: el santo grial de WebRTCVideoconferencias: el santo grial de WebRTC
Videoconferencias: el santo grial de WebRTCSaúl Ibarra Corretgé
 
SylkServer: State of the art RTC application server
SylkServer: State of the art RTC application serverSylkServer: State of the art RTC application server
SylkServer: State of the art RTC application serverSaúl Ibarra Corretgé
 
Escalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincherasEscalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincherasSaúl Ibarra Corretgé
 

Más 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

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
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
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"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
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
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
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 

Último (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
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
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"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
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
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
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 

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