Greenlets: coroutines aren't stranger than generators ----------------------------------------------------- "Greenlets", derived from the "Tasklets" of the Stackless Python implementation, provide a lightweight threading mechanism. A greenlet is akin to a microthread, with the major difference that control flow transfers are explicit and deterministic. This brings to Python the generally unfamiliar notion of "coroutines". Python's own generators, introduced in the 2.2 release, are themselves a limited variant of coroutines. Generators allow us -- after some mind adjustments -- to write algorithms in a direct way instead of having to think or rewrite them as a call-back. Coroutines offer basically the same advantage in a wider range of problems that are traditionally solved with call-backs, and could provide foundations for writing GUI toolkits, web applications, game AI etc. in a direct style. ------------------------------------------- The "greenlet" package is a spin-off of Stackless (http://www.stackless.com), a version of CPython that supports micro-threads called "tasklets". Tasklets run pseudo-concurrently (typically in a single or a few OS-level threads) and are synchronized with data exchanges on "channels". A "greenlet", on the other hand, is a still more primitive notion of micro-thread with no implicit scheduling; coroutines, in other words. This is useful when you want to control exactly when your code runs. You can build custom scheduled micro-threads on top of greenlet; however, it seems that greenlets are useful on their own as a way to make advanced control flow structures. For example, we can recreate generators; the difference with Python's own generators is that our generators can call nested functions and the nested functions can yield values too. (Additionally, you don't need a "yield" keyword. A "yield" function would do just as well). One could say that greenlets enable a kind of "generator-like" coding style that doesn't necessarily impose an asymmetric consumer-producer model. Greenlets are provided as a C extension module for the regular unmodified interpreter, as part of the 'py' lib (http://codespeak.net/py). The talk will be focused on a few examples of usage of greenlets, hint at what kind of higher-level mechanisms they could be used to build, and also point at some features that can only be provided by the full Stackless Python.