[Stackless] Interruptable wait aka Receive with Timeout

Andrew Tutt tutt.andrew at gmail.com
Sat Apr 17 18:34:03 CEST 2010


This idiom has probably already been contributed, but the following code
implements "interruptable wait" which could also be thought of the opposite
way, as implementing receive() with a timeout.

Also, I've taken the liberty on the following code of actually using a small
sleep call between schedules. This, I have found massively decreases CPU
load while altering my performance very little. Your results may vary, but
as you may already be aware, there is no way that I can think of that one
can implement sleep that is not busy in stackless, so this is the next best
thing. You could easily extend it to make it tweak the length of the
time.sleep based on load of course.

def schedule():
    time.sleep(.02);
    stackless.schedule()

# Wait related logic.
WaitList = []

# If you want to wait in a way where you can be woken
# By default, all waits are wakable
def wait(secondsToWait,channel=None):
    if channel is None:
        channel = stackless.channel()

    global WaitList
    endTime = time.time() + secondsToWait
    WaitList.append((endTime, channel))
    WaitList.sort()
    tasklet(CheckWaitlist)()
    channel.receive()

def wake(channel):
    global WaitList
    # Delete from the WaitList
    if channel in WaitList[:][0]:
        for i in WaitList:
            if channel in i: WaitList.remove(i)

    # If it's waiting, interrupt it
    channel.send(None)

def CheckWaitlist():
    global WaitList
    while len(WaitList):
        endTime = WaitList[0][0]
        if endTime <= time.time():
            channel = WaitList[0][1]
            del WaitList[0]
            # We have to send something, but it doesn't matter what as it is
not used.
            channel.send(None)
            WaitList.sort()
        schedule()
    # Else we don't schedule and so never again check

def run():
    stackless.run()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.stackless.com/pipermail/stackless/attachments/20100417/972bcb7a/attachment.htm>


More information about the Stackless mailing list