[Stackless] Asynchronous channel.send 'queue'

Bob Ippolito bob at redivi.com
Tue Feb 17 19:51:54 CET 2004


I seem to find myself wanting to send messages to channels from the 
main tasklet, and have had to use a paradigm like this:

import stackless

class TaskletSender(object):
     """
     This takes care of letting us send stuff to channels
     from the main tasklet, without worrying about blocking.
     """
     def __init__(self):
         """
         Please note that the queue I'm using here is in no way
         efficient, but it will never have a large backlog or anything
         so it doesn't particularly matter
         """
         self.queue = []
         self.tasklet = stackless.tasklet(self._tasklet)()
         self.channel = stackless.channel()

     def send(self, channel, data):
         self.queue.append((channel, data))

     def flush(self):
         if self.channel.balance < 0:
             self.channel.send('ping')
         elif self.channel.balance > 0:
             raise RuntimeError, "This shouldn't happen"

     def isWorking(self):
         return (self.channel.balance == 0)

     def _tasklet(self):
         queue = self.queue
         waker = self.channel
         while True:
             # dispatch all messages
             while queue:
                 channel, data = queue.pop(0)
                 channel.send(data)
             # wait until we have a message from the main tasklet
             waker.receive()


... later on

         unfinished = True
         t = time.time() + RESPONSETIME
         ctr = itertools.count()
         while unfinished and time.time() < t:
             stackless.tasklet(sender.flush)()
             stackless.run(MAXPYTHONOPS)
             # just ignore self._tasklet here, it's not important to the 
example
             unfinished = sender.isWorking() or (self._tasklet.blocked 
== 0)
             ctr.next()
         print >>_stderr, "ctr = ", ctr.next()

Is there a better way?

-bob


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



More information about the Stackless mailing list