[Stackless] Coroutines

Christian Tismer tismer at stackless.com
Thu May 27 18:34:49 CEST 2004


Jimmie Houchin wrote:

> Thanks,
> 
> I'll give that a try.

Note that this is a simple, flat example, just like
generators.
But you can pass that channel around into any deeper
recursion or other function call.
At the moment, this is directed, one can send, one
receive. I will have a channel.transfer() function,
soon, which is undirected and exchanges data.

You can emulate this like so:

class xchannel:
	def __init__(self):
		self.c1 = channel()
		self.c2 = channel()
	def transfer(self, val):
		if self.c1.balance > 0:
			retval = self.c1.receive()
			self.c2.send(val)
		else:
			self.c1.send(val)
			retval = self.c2.receive()
		return retval
	
from stackless import *

def coro1(ch):
     print "this is coro1"
     for i in range(10):
         ret = ch.transfer("coro1 is sending %d" %i)
         print "coro 1 got this back after transfer:", ret

def coro2(ch):
     print "this is coro2"
     for i in range(10):
         ret = ch.transfer("coro2 is sending %d" %i)
         print "coro 2 got this back after transfer:", ret

ch=xchannel()
tasklet(coro1)(ch)
tasklet(coro2)(ch)
run()


cheers - chris

-- 
Christian Tismer             :^)   <mailto:tismer at stackless.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34  home +49 30 802 86 56  mobile +49 173 24 18 776
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/


_______________________________________________
Stackless mailing list
Stackless at stackless.com
http://www.stackless.com/mailman/listinfo/stackless



More information about the Stackless mailing list