Views
NonblockingChannel
last edited 4 years ago by sholloway
Example: Nonblocking Channel:
import stackless
class NonblockingChannel(stackless.channel):
def send(self, value, wait=False):
if wait or self.balance < 0:
# there are tasklets waiting to receive
return stackless.channel.send(self, value)
def send_exception(self, exc, value, wait=False):
if wait or self.balance < 0:
# there are tasklets waiting to receive
return stackless.channel.send_exception(self, exc, value)
def receive(self, default=None, wait=False):
if wait or self.balance > 0:
# there are tasklets waiting to send
return stackless.channel.receive(self)
else:
return default
def testNonblockingChannel():
print
print "testNonblockingChannel"
print "----------------------"
def recv(ch, name):
print "Started recv<%s>" % (name,)
print "recv<%s>: got a message from \\"%s\\"" % (name, ch.receive(wait=True))
ch.send(name)
ch = NonblockingChannel()
ch.receive() # nonblocking receive
ch.send("nonblocking!") # nonblocking send
for name in "ABCDE":
task = stackless.tasklet(recv)(ch, name)
task.run()
ch.send('host')
print
testNonblockingChannel() should print:
testNonblockingChannel
----------------------
Started recv<A>
Started recv<B>
Started recv<C>
Started recv<D>
Started recv<E>
recv<A>: got a message from "host"
recv<B>: got a message from "A"
recv<C>: got a message from "B"
recv<D>: got a message from "C"
recv<E>: got a message from "D"
Stackless Python