greenlets and how they can be used

Mark Wooding mdw at distorted.org.uk
Sat Jan 3 10:00:22 EST 2009


James Mills <prologic at shortcircuit.net.au> wrote:

> The "greenlet" from http://codespeak.net/py/dist/greenlet.html
> is a rather interesting way of handling flow of control.

Ahh, yes.  It's actually a rather old idea, but too rarely used.

> What can "greenlet"'s be used for ? What use-cases have you guys used
> them for (if any) ?

I've one project in which I use coroutines (either greenlets or some
coroutines I concocted out of Python's built-in threading) extensively.
The system consists of a server which speaks a text-based protocol
(written in C), a graphical monitor program, and a number of ancillary
services which are both clients of the server, and augment it by
providing additional commands.  The monitor and the services are all in
Python, and make extensive use of coroutines.

One reason for this is that some of the server's commands can take a
long time, so it's useful for the programs to be able to do other things
while they wait for replies.  Full-on threading would be possible, but
(a) in fact I make a /lot/ of coroutines, and (b) with coroutines I
don't have to think anywhere near as hard about synchronization.

You can browse about here, if you like:

  http://git.distorted.org.uk/gitweb/~mdw/tripe?a=tree;h=python

The main Python module is in py/; the services are in svc/, and the
graphical monitor is in mon/.

> Can they be used in place of threads with much the same effect - but
> more lightweight ?

More lightweight, and much easier to reason about.  They also confuse
other libraries less.

-- [mdw]



More information about the Python-list mailing list