fiber(cooperative multi-threading)

Akihiro KAYAMA kayama at st.rim.or.jp
Sun Dec 23 04:16:31 EST 2007


Thanks for your replies.

In article <37c5a53c-1a39-47af-8983-d241e39bcb5c at i72g2000hsd.googlegroups.com>,
Arnaud Delobelle <arnodel at googlemail.com> writes:

arnodel> def f1():
arnodel>     print "f1 start"
arnodel>     yield f2,
arnodel>     print "f1 foo"
arnodel>     v = yield f2,
arnodel>     print "f1 v=%s world" % v
arnodel>     yield f2, "OK"
arnodel>     print "f1 end"
arnodel> 
arnodel> def f2():
arnodel>     print "f2 start"
arnodel>     yield f1,
arnodel>     print "f2 bar"
arnodel>     result = yield f1, "Hello, "
arnodel>     print "f2 result=%s" % result
arnodel>     print "f2 end"
arnodel>     yield f1,

This is the most simple example. In real programming, things are more
complicate so I will want to refactor it like below:

def foo(fiber, s, arg=None)
    print s
    return yield fiber, arg

def f1():
    foo(f2, "start")	# XXX returns generator object
    v = foo(f2, "foo")
    foo(f2, "v=%s world" % v, "OK")

But current Python generator specification requires me:

def f1():
    for x in foo(f2, "foo"): yield x
    for x in foo(f2, "foo"): yield x
    # XXX v = ... (I don't know how to do this)
    for x in foo(f2, "v=%s world" % v, "OK"): yield x

I think it is not straitforward. Single level function which generator
impose is impractical for real use.

In article <Xns9A0E94C1BC593duncanbooth at 127.0.0.1>,
Duncan Booth <duncan.booth at invalid.invalid> writes:

duncan.booth> Unfortunately generators only save a single level of stack-frame, so they 
duncan.booth> are not really a replacement for fibers/coroutines. The OP should perhaps 
duncan.booth> look at Stackless Python or Greenlets. See 
duncan.booth> http://codespeak.net/py/dist/greenlet.html

I am happy if I could use convenient coroutine features via standard
or simple extension library.  py.magic.greenlet may be what I'm
looking for, but I wonder why this is named "magic" :-)

-- kayama



More information about the Python-list mailing list