Every Python developer eventually hits the same wall. You need ten thousand concurrent tasks, OS threads cost real memory and scheduler pressure for each one, the GIL serializes the CPU-bound ones anyway, and async/await demands that you repaint your entire call graph with await keywords from main() down to every last helper. It is widely recognized that the greenlet package offers a fourth way: a small C extension for CPython that can suspend an entire call stack in the middle of any function and resume it later, with no await anywhere and no kernel involvement at all.

The cost of that trick is that the hard part lives in C and assembly, not Python. When gevent — the monkey-patching concurrency library — goes wrong, the segfault or leaked frame is hiding in code most Python programmers have never opened. That is a shame, because the greenlet codebase is one of the most instructive C extensions in the ecosystem: it has to freeze a live C stack, spill it to the heap, restore another one, and convince the interpreter that nothing strange just happened, all while keeping the garbage collector happy.

This post is a source tour of the real master tree of python-greenlet/greenlet (the version string in src/greenlet/__init__.py reads 3.5.7.dev0 at the time of writing). The layout surprises people: there is exactly one compiled C++ source file, a handful of T*.cpp implementation fragments it includes, a compile-time dispatcher to 24 hand-written platform headers, and a test suite that treats reference-count drift as a release blocker. Let’s walk it.

greenlet architecture overview: Python package, extension core, class hierarchy, stack switching, and saved state

Overview of greenlet on master: the Python facade on the left collapses into one unity-built extension, whose class hierarchy drives the slp_switch machinery and the heap-copied stack state on the right.

Reading the overview from left to right:

greenlet detail diagram: module bootstrap, C API surface, class hierarchy, switch core, saved state, tests, and build

The detail view adds the module bootstrap, the switch/throw method surface, the saved-state fragments, and the leak-hunting test suite that surrounds the core.

One translation unit, twelve exported pointers

The first thing that stands out is the build shape. setup.py compiles a single source file — sources=['src/greenlet/greenlet.cpp'] on setup.py, L155 — into the extension named greenlet._greenlet on setup.py, L153. That file then glues the whole implementation together by including each T*.cpp fragment: the greenlet classes, the state holders, and finally PyModule.cpp at greenlet.cpp, L204. A unity build like this keeps internal symbols file-local and avoids exporting a tangle of C++ symbols from a shared library.

Module initialization is refreshingly explicit. PyInit__greenlet readies PyGreenlet_Type, allocates the global GreenletGlobals, publishes the greenlet and UnswitchableGreenlet types plus the error and GreenletExit exceptions, and fills a static _PyGreenlet_API array of function pointers — PyGreenlet_New, PyGreenlet_GetCurrent, PyGreenlet_Throw, PyGreenlet_Switch, PyGreenlet_SetParent, and a few former macros, wrapped in a PyCapsule named greenlet._C_API at greenlet.cpp, L273. The header commits to exactly PyGreenlet_API_pointers 12 on greenlet.h, L35, which is the number downstream C extensions rely on.

One quirk worth knowing: the module deliberately copies getcurrent, error, GreenletExit, settrace, and gettrace onto the greenlet class itself — the copy_on_greentype table at PyModule.cpp, L273 — so greenlet.getcurrent() works even though the function really lives on the module. The source carries an honest comment admitting this is a confusing legacy pattern that shouldn’t grow.

From switch() to assembly and back

The Python-visible surface is tiny. The switch method on the type is green_switch at PyGreenlet.cpp, L373; it stashes the call arguments into the target’s pimpl and invokes g_switch(). From there, UserGreenlet::g_switch() at TUserGreenlet.cpp, L118 runs a deceptively simple while (target) loop: dead greenlets are skipped, arguments are pushed onto the parent, unstarted targets are bootstrapped through g_initialstub(&dummymarker) at TUserGreenlet.cpp, L185, and already-running targets go straight to g_switchstack(). If the target has no live parent, target = target->parent() at TUserGreenlet.cpp, L203 walks the chain — that walk is the famous greenlet parenting rule in action.

The bootstrap is where the code earns its reputation. g_initialstub grabs self.run (which can execute arbitrary Python and even switch greenlets), builds a fresh StackState from a stack marker, then calls g_switchstack() at TUserGreenlet.cpp, L299 — a call the comment honestly describes as returning twice: once in the new greenlet, once back in the caller. Eventually inner_bootstrap calls the user’s run callable through PyObject_Call at TUserGreenlet.cpp, L472.

The actual context flip is Greenlet::g_switchstack() at TGreenlet.cpp, L146. It saves the outgoing greenlet’s interpreter state (python_state << tstate), sets the file-scope switching_thread_state pointer to the incoming greenlet, and calls slp_switch(). That global — a static Greenlet* volatile at greenlet_slp_switch.hpp, L42, or thread_local under free-threaded builds — exists because the assembly below cannot safely pass extra arguments; the comment at greenlet_slp_switch.hpp, L33 documents that threading the state through this pointer nets a 10–12% switching speedup. After the flip, code reloads the pointer because no stack variable is valid anymore — the function’s own frame was just memcpy’d out from under itself. And if slp_switch() fails, there is no recovery: TGreenlet.cpp, L196 calls Py_FatalError because the stack is assumed corrupt. That hard failure mode is a useful contrast with stackful runtimes in Go, where the runtime owns the stacks and can grow them instead of copying them.

From one .c file to 24 switch headers

The platform layer is the part engineers love to read. greenlet_slp_switch.hpp defines the SLP_SAVE_STATE / SLP_RESTORE_STATE macros at greenlet_slp_switch.hpp, L52 and then, through #include "slp_platformselect.h", lets each platform inject its own slp_switch(). The dispatcher is a pure preprocessor chain starting at slp_platformselect.h, L8: MSVC x86, MSVC x64, MSVC ARM64, GCC x32, amd64, i386, PowerPC in four flavors, SPARC, S/390, ARM32, MIPS, aarch64, m68k, csky, RISC-V, DEC Alpha, LoongArch64, SuperH — 24 switch_*.h files in total under src/greenlet/platform/.

Each header is a masterclass in ABI pragmatics. The aarch64 GCC implementation defines REGS_TO_SAVE as x19–x28, x30 and v8–v15 at switch_aarch64_gcc.h, L19, captures the stack pointer with mov %0, sp, and adjusts both sp and the frame pointer with add sp,sp,%0 at switch_aarch64_gcc.h, L82. There is even a workaround comment for GCC 4.8 clobbering x0, fixed by forcing the return value with mov %w0, #0 at switch_aarch64_gcc.h, L117. The MSVC x64 path takes a different route entirely: it defines STACK_MAGIC 0 and EXTERNAL_ASM at switch_x64_msvc.h, L34, so the real slp_switch lives in a prebuilt MASM object (switch_x64_masm.obj) that setup.py, L141 links in on 64-bit Windows.

The build file itself encodes years of scar tissue. MSVC compiles with /EHsr at setup.py, L89 (always-generate checks in noexcept blocks, which the code relies on), fiber-safe TLS via /GT at setup.py, L110, and /std:c++20 at setup.py, L115. A RISC-V miscompile workaround appends -Os at setup.py, L60 after an assembler error in the inline-asm header. None of this is optional decoration; removing any line breaks a real platform.

Saving a live C stack to the heap

The data model behind all of this is five plain fields. StackState at TGreenlet.hpp, L212 holds _stack_start, stack_stop, stack_copy, _stack_saved, and stack_prev at TGreenlet.hpp, L222 — deliberately POD, as the comment explains, to keep the object tiny and its move semantics explicit. The big block comment at the top of greenlet.cpp, L114 draws the layout: a greenlet’s data is partly still in place on the C stack and partly saved in the heap, chained through stack_prev by address order, not execution order.

When a greenlet is switched out, copy_stack_to_heap_up_to() at TStackState.cpp, L106 grows the heap buffer with PyMem_Realloc and copies the freshly dirtied region with memcpy at TStackState.cpp, L127. Switching back in reverses it: copy_heap_to_stack() memcpys the saved bytes over the live stack and frees the buffer at TStackState.cpp, L91. The main greenlet is special-cased by sentinel: main() returns true when stack_stop == (char*)-1 at TStackState.cpp, L171, the “largest possible address” that owns the rest of the stack. This copying scheme is the same lineage as the Stackless Python technique the slp_ prefix preserves.

The class tree and the GC minefield

The C++ side is a compact hierarchy: abstract Greenlet at TGreenlet.hpp, L370, UserGreenlet at L714, MainGreenlet at L791, and BrokenGreenlet : public UserGreenlet at TGreenlet.hpp, L770, a test-only subclass whose force_slp_switch_error() makes the fatal switch path testable. Each greenlet owns three state objects — StackState, PythonState (interpreter fields saved around a switch in TPythonState.cpp), and ExceptionState — plus a per-thread ThreadState at TThreadState.hpp, L90 tracking the current greenlet and a pending-cleanup list.

Because greenlets participate in reference cycles, the type implements tp_traverse and tp_clear at TGreenlet.hpp, L516 and subsequent lines, and the team treats leaks as test failures. leakcheck.py provides a LeakCheckError at tests/leakcheck.py, L121 and a _RefCountChecker at tests/leakcheck.py, L153 that re-runs a test until refcounts stabilize and fails on growth; test_leaks.py uses it heavily, test_weakref.py pins down deallocation of dead greenlets at tests/test_weakref.py, L9, and the main behavioural suite test_greenlet.py runs about 1,500 lines. There are even fail_*.py scripts that intentionally crash to exercise the fatal paths.

Honest Limits

Reading the source also tells you what greenlet is not. It is not a scheduler — there is no ready queue, no I/O integration, no fairness; gevent supplies all of that on top, which is why the two projects are usually discussed together. Switching is explicitly single-threaded per greenlet: check_switch_allowed() refuses cross-thread switches, and the code is honest that a greenlet running in a dead thread leaves you holding a bogus thread-state pointer. The stack-copying model is also inherently fragile at the edges — the maintainers themselves describe the failed-slp_switch case as probably unrecoverable, and C++ exceptions escaping a greenlet lead straight to termination. If you want preemptive parallelism, OS threads or multiprocessing are still the answer; greenlet buys you cheap cooperative concurrency on one thread — the same bargain the event loop in Node.js makes, just with full call stacks instead of closures — and nothing more. Within that scope, though, the engineering discipline here — twelve exported API pointers, 24 platform headers, leak-checked tests — is exactly the kind of foundation code worth studying before you build anything that freezes a stack.

Watch PyShine on YouTube

Contents