[Stackless] Stackless channel example
sdfrost at UCSD.Edu
sdfrost at UCSD.Edu
Tue Oct 22 22:41:59 CEST 2002
Dear Stackless list,
It seems that some more (simple!) examples of tasklets and channels may be
helpful to newbies to Stackless (including myself). Here is a trivial discrete
event simulation in Stackless. I'd be very grateful to Christian to get some
idea of how stable the implementation of channels will be in future releases.
Best wishes
Simon
#!/usr/local/bin/python2.2s
# (or whatever your Stackless binary is)
"""
stackless_agent.py
Author: Simon Frost
Date: 22/10/2002
This is a very simple demonstration of channels in Stackless Python.
Agents are added to a World; initially these are uninfected (self.infected=0).
They wait on their own channel until they receive some (random) data, which
tells them
whether they are infected (1) or not (0). They send their status to the World,
which prints out their status and files a report.
"""
import stackless
import random
class Agent:
def __init__(self,world):
self.infected=0
self.channel=stackless.channel()
self.world=world
def live(self):
self.data=self.channel.receive()
self.infected=self.data
if self.infected==1:
self.world.channel.send(str(self)+" infected!")
elif self.infected==0:
self.world.channel.send(str(self)+" escaped infection!")
class World:
def __init__(self,numAgents):
self.agentList=[]
self.channel=stackless.channel()
for i in range(numAgents):
self.agentList.append(Agent(self))
def report(self):
result=[]
for agent in self.agentList:
result.append(agent.infected)
print result
def go(self):
for agent in self.agentList:
stackless.tasklet(agent.live)()
r=random.random()
if r < 0.5:
agent.channel.send(0)
else:
agent.channel.send(1)
print(self.channel.receive())
w=World(10)
w.report()
w.go()
w.report()
_______________________________________________
Stackless mailing list
Stackless at www.tismer.com
http://www.tismer.com/mailman/listinfo/stackless
More information about the Stackless
mailing list