SlideShare a Scribd company logo
Stack switching
for fun & profit
Saúl Ibarra Corretgé - @saghul
FOSDEM 2014
Hi!
@saghul
FOSDEM
Open Source
import open_source

github.com/saghul
Some background
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
Spin-off Stackless
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?
‘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
Stack switching for fun and profit
Stack switching for fun and profit
Stack switching for fun and profit
How does it work? (II)
Organized in a tree structure
Each greenlet has a ‘parent’, except main

Execution order isn’t always obvious
Example (II)
import greenlet

main = greenlet.getcurrent()
def foo_async(cb):
# Will 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)
main.switch()
Stackless Python
Fork of CPython, first release in 1999
Provides tasklets and channels
Builtin scheduler
Different approaches to switching
Stackless Python (II)
Different ways of switching: soft and hard
Soft switching
“Move some pointers around”

Hard switching
Platform dependent assembly code
When soft-switching is not possible
Enter PyPy
New shiny and fast implementation of Python
Vast amount of fairy-dust covered unicorns
included
Includes implementations of both greenlet and
Stackless
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;
}
import fibers
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
fibers API
Fiber(target=None, args=(), kwargs={},
parent=None): creates a new fiber which will run
“target(*args, **kwargs)”
Fiber.switch(value=None): switch execution to the
target fiber, value can only be passed after the
fiber is running
Fiber.throw(typ, [value, [tb]]): switch execution to
the target fiber and raise the specified exception
Motivation
Couldn’t build the API I wanted on top of greenlet
Early binding
More exceptions in expected places
No magic exceptions (GreenletExit)
No switching on GC
Example
import fibers

main = fibers.current()
def foo(n):
main.switch(n)
def bar(n):
foo(n)
return 'hello'

g1 = fibers.Fiber(target=bar, args=(42,))
print g1.switch()
# 42
print g1.switch()
# 'hello'
print g1.is_alive() # False
Projects using fibers
github.com/saghul/evergreen
github.com/geertj/gruvi
github.com/benoitc/offset

Should I add yours here?
The Stacklet Sandwich (TM)
greenlet / stackless / fibers

continulet

stacklet
Questions?

@saghul
bettercallsaghul.com

More Related Content

PDF
Understanding greenlet
KEY
Gevent what's the point
RTF
PPTX
Javascript Function
ODP
Stackless Python 101
PPTX
Javascript function
PDF
Andrii Orlov "Generators Flexibility in Modern Code"
PPTX
Queue oop
Understanding greenlet
Gevent what's the point
Javascript Function
Stackless Python 101
Javascript function
Andrii Orlov "Generators Flexibility in Modern Code"
Queue oop

What's hot (20)

PDF
The async/await concurrency pattern in Golang
PPTX
Command line arguments
PPT
Animation in Java
PPT
OO JS for AS3 Devs
PDF
Effective Modern C++ - Item 35 & 36
PDF
Use C++ to Manipulate mozSettings in Gecko
PPTX
Variadic functions
PPTX
Java Performance Tweaks
PDF
KOTLIN COROUTINES - PART 1
DOCX
PPT
Function
PDF
Go on!
PDF
Performance testing of microservices in Action
PDF
Rust Synchronization Primitives
PDF
Quick 入門 | iOS RDD テストフレームワーク for Swift/Objective-C
PDF
[2019] Java에서 Fiber를 이용하여 동시성concurrency 프로그래밍 쉽게 하기
PDF
PDF
視覚化とSwiftのタイプについて
PPTX
Data Types and Processing in ES6
The async/await concurrency pattern in Golang
Command line arguments
Animation in Java
OO JS for AS3 Devs
Effective Modern C++ - Item 35 & 36
Use C++ to Manipulate mozSettings in Gecko
Variadic functions
Java Performance Tweaks
KOTLIN COROUTINES - PART 1
Function
Go on!
Performance testing of microservices in Action
Rust Synchronization Primitives
Quick 入門 | iOS RDD テストフレームワーク for Swift/Objective-C
[2019] Java에서 Fiber를 이용하여 동시성concurrency 프로그래밍 쉽게 하기
視覚化とSwiftのタイプについて
Data Types and Processing in ES6
Ad

Viewers also liked (20)

PDF
OpenStack Neutron: What's New In Kilo and a Look Toward Liberty
DOCX
Dipak Gade
ODP
VPC Implementation In OpenStack Heat
PDF
OpenStack Tokyo Summit Keynote Slides
PDF
Unlocked London - Technical Track
PDF
Everything as Code
PPTX
Network and Service Virtualization tutorial at ONUG Spring 2015
ODP
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
PDF
Polyglot Persistence
PPTX
System Administrator PowerPoint
PDF
Cisco UCS for OpenStack Cloud
PDF
Unlocked London - Case Studies
PPT
Getting Started With OpenStack (Havana)
ODP
OpenStack DevStack Tutorial
PDF
OVN: Scaleable Virtual Networking for Open vSwitch
PPTX
Openstack in 10 mins
PPTX
OpenStack and OpenDaylight Workshop: ONUG Spring 2014
PDF
UCS Overview and Update
PPTX
OpenStack: Changing the Face of Service Delivery
PPTX
OpenStack + VMware: Everything You Need to Know (Kilo-edition)
OpenStack Neutron: What's New In Kilo and a Look Toward Liberty
Dipak Gade
VPC Implementation In OpenStack Heat
OpenStack Tokyo Summit Keynote Slides
Unlocked London - Technical Track
Everything as Code
Network and Service Virtualization tutorial at ONUG Spring 2015
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
Polyglot Persistence
System Administrator PowerPoint
Cisco UCS for OpenStack Cloud
Unlocked London - Case Studies
Getting Started With OpenStack (Havana)
OpenStack DevStack Tutorial
OVN: Scaleable Virtual Networking for Open vSwitch
Openstack in 10 mins
OpenStack and OpenDaylight Workshop: ONUG Spring 2014
UCS Overview and Update
OpenStack: Changing the Face of Service Delivery
OpenStack + VMware: Everything You Need to Know (Kilo-edition)
Ad

Similar to Stack switching for fun and profit (20)

PPT
Thread
ODP
Software Transactioneel Geheugen
PDF
Lockless
PPT
Unit 4
PPTX
Templates
PDF
PPTX
Flink Batch Processing and Iterations
PDF
GPU Programming on CPU - Using C++AMP
PDF
Software transactional memory. pure functional approach
PDF
Programming For Big Data [ Submission DvcScheduleV2.cpp and StaticA.pdf
DOCX
package algs13;import stdlib.;import java.util.Iterator;im.docx
PDF
Kotlin coroutine - the next step for RxJava developer?
PDF
Kotlin - Coroutine
PDF
Writing native bindings to node.js in C++
PDF
Giorgio zoppi cpp11concurrency
PDF
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
DOCX
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
KEY
W3C HTML5 KIG-How to write low garbage real-time javascript
PPTX
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
PPT
Deuce STM - CMP'09
Thread
Software Transactioneel Geheugen
Lockless
Unit 4
Templates
Flink Batch Processing and Iterations
GPU Programming on CPU - Using C++AMP
Software transactional memory. pure functional approach
Programming For Big Data [ Submission DvcScheduleV2.cpp and StaticA.pdf
package algs13;import stdlib.;import java.util.Iterator;im.docx
Kotlin coroutine - the next step for RxJava developer?
Kotlin - Coroutine
Writing native bindings to node.js in C++
Giorgio zoppi cpp11concurrency
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
W3C HTML5 KIG-How to write low garbage real-time javascript
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Deuce STM - CMP'09

More from Saúl Ibarra Corretgé (20)

PDF
JanusCon 2024: Mom there are robots in my meeting
PDF
Challenges running Jitsi Meet at scale during the pandemic
PDF
The Road to End-to-End Encryption in Jitsi Meet
PDF
Jitsi: State of the Union 2020
PDF
Jitsi Meet: our tale of blood, sweat, tears and love
PDF
Jitsi Meet: Video conferencing for the privacy minded
PDF
Jitsi - Estado de la unión 2019
PDF
Get a room! Spot: the ultimate physical meeting room experience
PDF
Going Mobile with React Native and WebRTC
PDF
Going Mobile with React Native and WebRTC
PDF
Jitsi: Estado de la Unión (2018)
PDF
Jitsi: state-of-the-art video conferencing you can self-host
PDF
WebRTC: El epicentro de la videoconferencia y IoT
PDF
Jitsi: Open Source Video Conferencing
PDF
Jitsi: State of the Union
PDF
libuv: cross platform asynchronous i/o
PDF
Videoconferencias: el santo grial de WebRTC
PDF
SylkServer: State of the art RTC application server
PDF
Escalabilidad horizontal desde las trincheras
PDF
A deep dive into libuv
JanusCon 2024: Mom there are robots in my meeting
Challenges running Jitsi Meet at scale during the pandemic
The Road to End-to-End Encryption in Jitsi Meet
Jitsi: State of the Union 2020
Jitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: Video conferencing for the privacy minded
Jitsi - Estado de la unión 2019
Get a room! Spot: the ultimate physical meeting room experience
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTC
Jitsi: Estado de la Unión (2018)
Jitsi: state-of-the-art video conferencing you can self-host
WebRTC: El epicentro de la videoconferencia y IoT
Jitsi: Open Source Video Conferencing
Jitsi: State of the Union
libuv: cross platform asynchronous i/o
Videoconferencias: el santo grial de WebRTC
SylkServer: State of the art RTC application server
Escalabilidad horizontal desde las trincheras
A deep dive into libuv

Recently uploaded (20)

PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Cloud computing and distributed systems.
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Encapsulation theory and applications.pdf
PPTX
Spectroscopy.pptx food analysis technology
PPT
Teaching material agriculture food technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Programs and apps: productivity, graphics, security and other tools
Network Security Unit 5.pdf for BCA BBA.
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Diabetes mellitus diagnosis method based random forest with bat algorithm
MIND Revenue Release Quarter 2 2025 Press Release
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
NewMind AI Weekly Chronicles - August'25 Week I
Dropbox Q2 2025 Financial Results & Investor Presentation
Cloud computing and distributed systems.
Advanced methodologies resolving dimensionality complications for autism neur...
Spectral efficient network and resource selection model in 5G networks
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Encapsulation theory and applications.pdf
Spectroscopy.pptx food analysis technology
Teaching material agriculture food technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Understanding_Digital_Forensics_Presentation.pptx

Stack switching for fun and profit

  • 1. Stack switching for fun & profit Saúl Ibarra Corretgé - @saghul FOSDEM 2014
  • 4. Some background Who knows what greenlet is? Who has used it (standalone)? Who understands how it works?
  • 5. Greenlet Micro-threads with no implicit scheduling Lightweight Only one can run at a time Spin-off Stackless
  • 6. 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)
  • 7. 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
  • 8. How does it work? ‘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
  • 12. How does it work? (II) Organized in a tree structure Each greenlet has a ‘parent’, except main Execution order isn’t always obvious
  • 13. Example (II) import greenlet main = greenlet.getcurrent() def foo_async(cb): # Will 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) main.switch()
  • 14. Stackless Python Fork of CPython, first release in 1999 Provides tasklets and channels Builtin scheduler Different approaches to switching
  • 15. Stackless Python (II) Different ways of switching: soft and hard Soft switching “Move some pointers around” Hard switching Platform dependent assembly code When soft-switching is not possible
  • 16. Enter PyPy New shiny and fast implementation of Python Vast amount of fairy-dust covered unicorns included Includes implementations of both greenlet and Stackless Implemented on top of “continulet” objects
  • 17. import _continuation Continulets are one-shot continuations Switching code is a standalone C library: stacklet rpython/translator/c/src/stacklet/
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. #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; }
  • 22. import fibers 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
  • 23. fibers API Fiber(target=None, args=(), kwargs={}, parent=None): creates a new fiber which will run “target(*args, **kwargs)” Fiber.switch(value=None): switch execution to the target fiber, value can only be passed after the fiber is running Fiber.throw(typ, [value, [tb]]): switch execution to the target fiber and raise the specified exception
  • 24. Motivation Couldn’t build the API I wanted on top of greenlet Early binding More exceptions in expected places No magic exceptions (GreenletExit) No switching on GC
  • 25. Example import fibers main = fibers.current() def foo(n): main.switch(n) def bar(n): foo(n) return 'hello' g1 = fibers.Fiber(target=bar, args=(42,)) print g1.switch() # 42 print g1.switch() # 'hello' print g1.is_alive() # False
  • 27. The Stacklet Sandwich (TM) greenlet / stackless / fibers continulet stacklet