Queued Channels in Stackless PyPy

PyPy implements Stackless‘s cooperative concurrency model. It uses a channel construct to synchronize hand-off of data between a sender and receiver. Unfortunately, it most cases it would be preferable to have a queued channel that supports asynchronous message passing between tasklets. So here’s a quick hack to make it work. I don’t think this will work if one uses preemptive scheduling.

class Qchannel(stackless.channel):

    def __init__(self, maxsize=0):
        stackless.channel.__init__(self)
        self.data = deque()

    def send(self, msg):
        self.data.append(msg)
        if self.balance < 0:
            stackless.channel.send(self,True)
        stackless.schedule()

    def receive(self):
        while len(self.data) == 0:
            stackless.channel.receive(self)
        v = self.data.popleft()
        stackless.schedule()
        return v 
Advertisements

One comment

  1. Erik Allik

    Why not:

    class Qchannel(channel):
    def __init__(self):
    super(Qchannel, self).__init__()
    self.pending = deque()

    def send(self, value):
    if self.balance < 0:
    super(Qchannel, self).send(value)
    else:
    self.pending.append(value)

    def receive(self):
    if self.pending:
    return self.pending.popleft()
    else:
    super(Qchannel, self).receive()

    What am I missing?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s