fibers: lightweight cooperative microthreads for Python

Hi all!

Today I’m really happy to share the first version of fibers, a project I’ve working on for a while.

Fibers are lightweight primitives for cooperative multitasking in Python. They provide means for running pieces of code that can be paused and resumed. Unlike threads, which are preemptively scheduled, fibers are scheduled cooperatively, that is, only one fiber will be running at a given point in time, and no other fiber will run until the user explicitly decides so.

When a fiber is created it will not run automatically. A fiber must be ‘switched’ into for it to run. Fibers can switch control to other fibers by way of the switch or throw functions, which switch control or raise and exception in the target fiber respectively.

 

This project is heavily inspired by greenlet, as you may have noticed. I’ve been using greenlet for a long while, but for a recent project I’ve worked on, I wanted to offer an interface similar to the Thread class from the threading module. Unfortunately the API in greenlet didn’t make it easy, so I took it as an excuse to try to build the library I wanted to use, which hopefully also helps others.

The obvious step would have been to fork greenlet itself and change the API to my needs, but I randomly ran into stacklet, a tiny library hidden in the PyPy source code, which is used as the base for the greenlet implementation in PyPy.

So, I stood on shoulders of giants and built fibers using stacklet. It solves my problems, hopefully it can help you too! In case you are interested in a more verbose version of the project rationale, I added a specific section in the documentation.

The source code is available on GitHub, with MIT license, enjoy!

import fibers

def runner(*args, **kw):
    print "hello, I'm running inside a fiber! - %r" % fibers.current()

f = fibers.Fiber(target=runner)
f.switch()

:wq