[Stackless] Video on channels

Hallgrimur H. Gunnarsson hhg at hhg.to
Sun Sep 9 14:48:16 CEST 2007


Hi,

I watched the same techtalk a while ago and after it I also translated the
prime sieve example into stackless python as an exercise. The outcome
was a little different from your version, see below (or http://hhg.to/sieve.py).

Also, for those who can't watch the techtalk, there are good explanations of
the concurrent prime sieve in Pike's slides for an earlier lecture:

http://herpolhode.com/rob/lec1.pdf

and also on Russ Cox's site on CSP and Bell Labs:

http://swtch.com/~rsc/thread/
http://swtch.com/~rsc/talks/group02-thread.pdf

. And finally the code:

import stackless
import sys

def counter(ch, i=1):
	while True:
		ch.send(i)
		i += 1

def sieve(prime):
	def filter(p, r, s):
		while True:
			x = r.receive()
			if x % p: s.send(x)

	def applyfilter(ch, p):
		nch = stackless.channel()
		stackless.tasklet(filter)(p, ch, nch)
		return nch

	ch = stackless.channel()
	stackless.tasklet(counter)(ch, 2)

	while True:
		p = ch.receive()
		prime.send(p)
		ch = applyfilter(ch, p)

if __name__ == "__main__":
	try:
		if len(sys.argv) < 2:
			goal = 100
		else:
			goal = int(sys.argv[1])

		primes = stackless.channel()
		stackless.tasklet(sieve)(primes)

		for i in xrange(goal):
			print primes.receive()

	except TaskletExit:
		pass




More information about the Stackless mailing list